Assignment_13: - Java programs to understand GUI designing and event handling.
Java GUI design and event handling are primarily managed through
the Swing and AWT libraries. Modern Java development typically favours Swing for its
platform-independent, "lightweight" components.
1. Basic GUI Design (Swing)
To create a GUI, you must set up a top-level container, typically a JFrame, and add
components like buttons (JButton), labels (JLabel), or text fields (JTextField) to it.
Key Design Steps:
Initialize the Frame: Create a JFrame object to serve as the main window.
Set Properties: Define the window's size (setSize), title (setTitle), and close operation
(setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)).
Use Layout Managers: Organize components using managers
like FlowLayout, BorderLayout, or GridLayout.
Add Components: Instantiate components and add them to the frame or a JPanel.
2. Event Handling Mechanism
Java uses the Delegation Event Model, where a "source" generates an event and a "listener"
responds to it.
Event Source: The GUI component (e.g., a button) that the user interacts with.
Event Object: Automatically created when an interaction occurs, containing details
about the event.
Event Listener: An interface (e.g., ActionListener) that must be implemented to
define the response logic.
3. Example: Button Click Event
This example demonstrates a simple "Counter" application. Each time the button is clicked, a
label updates with the total click count.
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleClickCounter
private int count = 0;
public SimpleClickCounter()
// 1. Design: Setup Frame and Components
JFrame frame = new JFrame("Event Handling Demo");
JButton button = new JButton("Click Me!");
JLabel label = new JLabel("Count: 0");
// 2. Event Handling: Add ActionListener to the button
[Link](new ActionListener ()
public void actionPerformed(ActionEvent e)
count++;
[Link]("Count: " + count);
});
// 3. Layout: Add components to frame
[Link](new FlowLayout());
[Link](button);
[Link](label);
// 4. Display: Finalize window settings
[Link](300, 100);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
public static void main (String [] args)
new SimpleClickCounter();
Output: -