Advanced Programming with JavaUnit 77 min read
GUI Programming: Swing & JavaFX Basics, Layouts, Events & Animations
Unit 7 of Advanced Programming with Java covers Swing and JavaFX frameworks for building graphical user interfaces (GUIs) in Java, including components, layouts, event handling, and animations, with practical examples and code traces.
TAKEAWAYS:
- Swing vs. JavaFX: Swing is lightweight and built on AWT, while JavaFX is modern, hardware-accelerated, and supports CSS styling and multimedia.
- Layout Managers: Use
BorderLayout,GridLayout,FlowLayout, orGroupLayoutto organize components dynamically. - Event Handling: Implement
ActionListener,MouseListener, or lambda expressions to respond to user interactions. - Animations: Use
TimelineandKeyFramein JavaFX to create smooth transitions and effects. - Real-World Use: GUI frameworks power apps like eSewa’s payment interface (JavaFX for smooth animations) and Khalti’s dashboard (Swing for tabbed layouts).
1. Introduction to GUI Programming
Graphical User Interfaces (GUIs) allow users to interact with software visually. Java provides two frameworks:
- Swing: Part of Java SE, lightweight, and built on AWT (Abstract Window Toolkit).
- JavaFX: Modern, hardware-accelerated, and designed for rich media applications.
Swing vs. JavaFX: Comparison Table
| Feature | Swing | JavaFX |
|---|---|---|
| Performance | Software-rendered | Hardware-accelerated (GPU) |
| Styling | Limited (via UIManager) |
CSS-based styling |
| Multimedia | Basic support | Full support (video, audio) |
| Learning Curve | Easier for beginners | Steeper due to FXML/Scene Builder |
2. Swing Basics
Swing provides reusable components like buttons, text fields, and panels. Key classes:
JFrame: Main window container.JPanel: Holds other components.JButton,JLabel,JTextField: Common UI elements.
Example: Simple Swing Window
import javax.swing.*;
public class SimpleSwingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello Swing");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
frame.add(button);
frame.setVisible(true);
}
}
Visual Trace:
JFrameis created with title "Hello Swing".JButtonis added to the frame.setVisible(true)displays the window.
3. Layout Managers in Swing
Layout managers arrange components dynamically. Common ones:
- BorderLayout: Divides space into 5 areas (NORTH, SOUTH, EAST, WEST, CENTER).
- GridLayout: Arranges components in a grid.
- FlowLayout: Places components left-to-right, top-to-bottom.
Example: BorderLayout Usage
JFrame frame = new JFrame("BorderLayout Demo");
frame.setLayout(new BorderLayout());
JButton northBtn = new JButton("North");
JButton southBtn = new JButton("South");
JButton eastBtn = new JButton("East");
JButton westBtn = new JButton("West");
JButton centerBtn = new JButton("Center");
frame.add(northBtn, BorderLayout.NORTH);
frame.add(southBtn, BorderLayout.SOUTH);
frame.add(eastBtn, BorderLayout.EAST);
frame.add(westBtn, BorderLayout.WEST);
frame.add(centerBtn, BorderLayout.CENTER);
Visual:
graph TD
A["BorderLayout Frame"] --> B["North"]
A --> C["South"]
A --> D["East"]
A --> E["West"]
A --> F["Center"]4. Event Handling in Swing
Events (e.g., button clicks) are handled using listeners. Example:
button.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "Button clicked!");
});
Trace:
- User clicks
JButton. ActionEventtriggersActionListener.JOptionPanedisplays a message.
5. JavaFX Basics
JavaFX uses a Scene Graph (nodes like Stage, Scene, Pane). Key classes:
Stage: Top-level window.Scene: Container for nodes.Button,Label,TextField: UI components.
Example: JavaFX Hello World
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloJavaFX extends Application {
@Override
public void start(Stage stage) {
Button btn = new Button("Click Me!");
btn.setOnAction(e -> System.out.println("Hello JavaFX!"));
StackPane root = new StackPane(btn);
Scene scene = new Scene(root, 300, 200);
stage.setScene(scene);
stage.show();
}
}
Visual Trace:
Stageis created and configured.Buttonis added to aStackPane.Sceneis set, andstage.show()displays the window.
6. Layouts in JavaFX
JavaFX uses Pane classes for layouts:
BorderPane: Similar to Swing’sBorderLayout.GridPane: Grid-based layout.HBox/VBox: Horizontal/vertical containers.
Example: GridPane Layout
GridPane grid = new GridPane();
grid.add(new Button("1"), 0, 0);
grid.add(new Button("2"), 1, 0);
grid.add(new Button("3"), 0, 1);
Visual:
graph TD
A["GridPane"] --> B["Button 1 (0,0)"]
A --> C["Button 2 (1,0)"]
A --> D["Button 3 (0,1)"]7. Animations in JavaFX
JavaFX supports animations via Timeline and KeyFrame. Example:
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(1), e -> {
button.setTranslateX(button.getTranslateX() + 10);
})
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
Visual Trace:
stateDiagram-v2
[*] --> Moving: Button moves right by 10px
Moving --> Moving: Every 1 secondIn the Real World
- eSewa’s Payment Interface
- Uses JavaFX animations for smooth transitions between payment steps (e.g., sliding panels for card details).
- Khalti’s Dashboard
- Employs Swing’s tabbed layout (
JTabbedPane) to organize transactions, profiles, and settings.
- Employs Swing’s tabbed layout (
- Nepal Stock Exchange (NEPSE) App
- Leverages JavaFX charts (
LineChart,BarChart) for real-time stock price visualization.
- Leverages JavaFX charts (
8. Worked Example: Bank ATM Simulation
Scenario: Simulate an ATM with a PIN input and balance check using Swing.
JFrame frame = new JFrame("ATM Simulation");
JTextField pinField = new JTextField(10);
JButton checkBalanceBtn = new JButton("Check Balance");
checkBalanceBtn.addActionListener(e -> {
String pin = pinField.getText();
if (pin.equals("1234")) {
JOptionPane.showMessageDialog(frame, "Balance: NPR 50,000");
} else {
JOptionPane.showMessageDialog(frame, "Invalid PIN!");
}
});
frame.add(pinField);
frame.add(checkBalanceBtn);
frame.setVisible(true);
Visual Trace:
- User enters PIN in
JTextField. - Clicks "Check Balance".
- If PIN is "1234", balance is displayed; else, error message appears.
Exam Tip
- Swing: Focus on
JFrame,JPanel, and layout managers. RemembersetVisible(true)is required to display a window. - JavaFX: Know
Stage,Scene, andTimelinefor animations. UsesetOnActionfor event handling. - Common Mistakes:
- Forgetting to call
pack()orsetSize()in Swing. - Not setting
cycleCountin JavaFX animations (defaults to1).
- Forgetting to call
- Practical Questions: Expect code snippets for GUI creation or event handling. Trace the flow of a simple animation or layout change.
Based on the PU BE Computer (PU) syllabus for Advanced Programming with Java (CMP228), unit 7.
Discussion
Loading…