0% found this document useful (0 votes)
1 views13 pages

Topic 9 - Graphical User Interface

good work

Uploaded by

samueld8448
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

Topic 9 - Graphical User Interface

good work

Uploaded by

samueld8448
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lecture Notes: Graphical User Interfaces in Java – AWT, Swing, Components, and

Event Handling
1. Introduction to GUI Programming in Java
Graphical User Interface (GUI) programming allows users to interact with applications using
windows, buttons, text fields, and mouse clicks rather than command-line text. Java provides
two main GUI toolkits: AWT (Abstract Window Toolkit) and Swing. Both are part of the
Java Foundation Classes (JFC). Understanding the differences between them is crucial for
choosing the right toolkit for your application.
AWT was the original GUI library, introduced with Java 1.0. Swing came later (Java 1.2,
1998) as a more powerful and flexible replacement. Both are still supported, but Swing is the
preferred choice for most desktop applications.
2. AWT (Abstract Window Toolkit) – The Original GUI Library
AWT uses native platform resources (peers) to create GUI components. When you create
an AWT button, the underlying operating system (Windows, macOS, Linux) creates a native
button. This means AWT applications look like native applications on each platform.
Characteristics of AWT:
 Lightweight in terms of code, but components are "heavyweight" (rely on native OS
peers)
 Fast rendering for basic components because the OS handles drawing
 Platform-dependent look-and-feel (a button looks different on Windows vs. macOS)
 Limited set of components (buttons, labels, text fields, checkboxes, lists, menus)
 No support for advanced features like icons, tooltips, or custom borders
 Uses a hierarchical event model (less flexible than Swing's)
Example AWT program:
java
import [Link].*;
import [Link].*;

public class AWTExample {


public static void main(String[] args) {
// Create a frame (window)
Frame frame = new Frame("AWT Window");

// Create a button
Button button = new Button("Click Me");

// Create a label
Label label = new Label("Hello from AWT");

// Set layout and add components


[Link](new FlowLayout());
[Link](label);
[Link](button);

// Add event handling (old-style)


[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

// Close window when user clicks close button


[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

[Link](300, 200);
[Link](true);
}
}
3. Swing – The Modern GUI Toolkit
Swing was introduced to overcome AWT's limitations. Swing components are lightweight –
they are written entirely in Java and do not rely on native OS peers (except for the top-level
containers like JFrame, JApplet, JDialog, and JWindow). Swing draws its own components
using Java 2D graphics.
Why we use Swing over AWT:
Feature AWT Swing

Component weight Heavyweight (native peers) Lightweight (Java-drawn)

Look and feel Platform-dependent (native) Pluggable (same everywhere or custom)

Rich (tables, trees, text panes, sliders,


Component set Limited (basic components)
etc.)

Tooltips Not supported Built-in support

Icons on buttons Not directly supported Supported (JButton with ImageIcon)

Borders None Extensive border library

Double buffering Manual Automatic (smoother rendering)

MVC architecture No Yes (Model-View-Controller)

Keyboard navigation Limited Comprehensive

Custom component Difficult (must override


Easy (override paintComponent())
creation native painting)
Key reasons to choose Swing:
1. Portability – Swing applications look consistent across all platforms (or you can
choose a specific look-and-feel like Nimbus, Motif, or Windows).
2. Richer
components – JTable, JTree, JSpinner, JSlider, JEditorPane, JColorChooser, JFileCh
ooser, and many more.
3. Extensibility – Easy to create custom components by extending JComponent.
4. Pluggable Look-and-Feel (PLAF) – You can change the entire appearance of your
application at runtime.
5. Better event handling – Uses a cleaner delegation event model with typed events and
adapters.
Example Swing program (equivalent to the AWT example):
java
import [Link].*;
import [Link].*;
import [Link].*;

public class SwingExample {


public static void main(String[] args) {
// Use [Link] for thread safety
[Link](() -> {
// Create frame
JFrame frame = new JFrame("Swing Window");
[Link](JFrame.EXIT_ON_CLOSE);

// Create components
JLabel label = new JLabel("Hello from Swing");
JButton button = new JButton("Click Me");

// Add icon to button (Swing advantage)


// [Link](new ImageIcon("[Link]"));

// Set layout and add components


[Link](new FlowLayout());
[Link](label);
[Link](button);

// Event handling with lambda


[Link](e -> [Link]("Button clicked!"));

[Link](300, 200);
[Link](true);
});
}
}
Note: Always create and manipulate Swing components on the Event Dispatch Thread
(EDT) using [Link](). This prevents threading issues.
4. Dialog Boxes in Swing
Dialog boxes are temporary windows that appear to request input, display messages, or
confirm actions. Swing provides JDialog for custom dialogs and JOptionPane for standard,
easy-to-use dialogs.
JOptionPane – Standard Dialogs:
java
import [Link].*;

public class DialogExamples {


public static void main(String[] args) {
// 1. Message dialog (information)
[Link](null,
"File saved successfully!",
"Success",
JOptionPane.INFORMATION_MESSAGE);

// 2. Warning dialog
[Link](null,
"Disk space is low",
"Warning",
JOptionPane.WARNING_MESSAGE);

// 3. Error dialog
[Link](null,
"Connection failed",
"Error",
JOptionPane.ERROR_MESSAGE);

// 4. Confirmation dialog (Yes/No/Cancel)


int response = [Link](null,
"Do you want to save changes?",
"Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);

if (response == JOptionPane.YES_OPTION) {
[Link]("User chose Yes");
} else if (response == JOptionPane.NO_OPTION) {
[Link]("User chose No");
} else {
[Link]("User cancelled");
}

// 5. Input dialog (get text from user)


String name = [Link](null,
"Enter your name:",
"Input",
JOptionPane.QUESTION_MESSAGE);

if (name != null && ![Link]().isEmpty()) {


[Link](null, "Hello, " + name + "!");
}

// 6. Custom option dialog (dropdown choices)


String[] options = {"Red", "Green", "Blue"};
int colorChoice = [Link](null,
"Choose your favorite color:",
"Color Selection",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
options,
options[0]);

if (colorChoice >= 0) {
[Link]("Selected: " + options[colorChoice]);
}
}
}
Custom Dialogs with JDialog:
When you need more complex dialogs with multiple custom components, extend JDialog:
java
import [Link].*;
import [Link].*;
import [Link].*;

class CustomLoginDialog extends JDialog {


private JTextField usernameField;
private JPasswordField passwordField;
private boolean succeeded = false;

public CustomLoginDialog(JFrame parent) {


super(parent, "Login", true); // true = modal dialog
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Username label and field


[Link] = 0; [Link] = 0;
add(new JLabel("Username:"), gbc);
[Link] = 1;
usernameField = new JTextField(15);
add(usernameField, gbc);

// Password label and field


[Link] = 0; [Link] = 1;
add(new JLabel("Password:"), gbc);
[Link] = 1;
passwordField = new JPasswordField(15);
add(passwordField, gbc);

// Buttons panel
JPanel buttonPanel = new JPanel();
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
[Link](loginButton);
[Link](cancelButton);
[Link] = 0; [Link] = 2;
[Link] = 2;
add(buttonPanel, gbc);

// Event handlers
[Link](e -> {
if (authenticate([Link](), new String([Link]())))
{
succeeded = true;
dispose();
} else {
[Link]([Link],
"Invalid username or password",
"Login Failed",
JOptionPane.ERROR_MESSAGE);
}
});

[Link](e -> dispose());

pack();
setLocationRelativeTo(parent);
}

private boolean authenticate(String username, String password) {


// Validate credentials (simplified)
return "admin".equals(username) && "secret".equals(password);
}

public boolean isSucceeded() {


return succeeded;
}
}
5. GUI Components in Swing
Swing provides a comprehensive set of components. Here are the most commonly used ones:
Basic Components:
java
import [Link].*;
import [Link].*;
import [Link].*;

public class ComponentDemo extends JFrame {


public ComponentDemo() {
setTitle("Swing Components Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(0, 2, 10, 10)); // 2 columns, auto rows

// JLabel – text or icon display


JLabel label = new JLabel("Name:");
JTextField textField = new JTextField(20);
add(label); add(textField);

// JPasswordField – masked input


add(new JLabel("Password:"));
add(new JPasswordField(20));

// JButton – clickable button


JButton button = new JButton("Submit");
[Link]("Click to submit the form");
add(new JLabel("Action:")); add(button);

// JCheckBox – multiple selection


JCheckBox javaCheck = new JCheckBox("Java");
JCheckBox pythonCheck = new JCheckBox("Python");
JPanel checkPanel = new JPanel(new FlowLayout());
[Link](javaCheck);
[Link](pythonCheck);
add(new JLabel("Languages:")); add(checkPanel);

// JRadioButton – single selection (use ButtonGroup)


JRadioButton maleRadio = new JRadioButton("Male");
JRadioButton femaleRadio = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
[Link](maleRadio);
[Link](femaleRadio);
JPanel radioPanel = new JPanel(new FlowLayout());
[Link](maleRadio);
[Link](femaleRadio);
add(new JLabel("Gender:")); add(radioPanel);

// JComboBox – dropdown selection


JComboBox<String> countryCombo = new JComboBox<>(new String[]{"Select",
"India", "USA", "UK", "Canada"});
add(new JLabel("Country:")); add(countryCombo);

// JList – selectable list


JList<String> colorList = new JList<>(new String[]{"Red", "Green", "Blue",
"Yellow"});

[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane listScroll = new JScrollPane(colorList);
[Link](new Dimension(100, 80));
add(new JLabel("Colors:")); add(listScroll);

// JTextArea – multi-line text


JTextArea textArea = new JTextArea(5, 20);
[Link](true);
JScrollPane textScroll = new JScrollPane(textArea);
add(new JLabel("Comments:")); add(textScroll);
// JSlider – numeric range input
JSlider slider = new JSlider(0, 100, 50);
[Link](20);
[Link](true);
[Link](true);
add(new JLabel("Volume:")); add(slider);

// JSpinner – numeric up/down


JSpinner spinner = new JSpinner(new SpinnerNumberModel(5, 1, 10, 1));
add(new JLabel("Quantity:")); add(spinner);

// JProgressBar – visual progress indicator


JProgressBar progressBar = new JProgressBar(0, 100);
[Link](65);
[Link](true);
add(new JLabel("Progress:")); add(progressBar);

// JTable – spreadsheet-like data


String[] columns = {"ID", "Name", "Age"};
Object[][] data = {
{1, "Alice", 25},
{2, "Bob", 30},
{3, "Charlie", 35}
};
JTable table = new JTable(data, columns);
JScrollPane tableScroll = new JScrollPane(table);
[Link](new Dimension(300, 100));
add(new JLabel("Data Table:")); add(tableScroll);

pack();
setLocationRelativeTo(null);
}

public static void main(String[] args) {


[Link](() -> new ComponentDemo().setVisible(true));
}
}
6. Event Handling in Swing
Event handling is the mechanism that makes GUI applications interactive. Swing uses
the delegation event model: a component (event source) generates an event when something
happens (click, key press, etc.), and that event is delegated to one or more listeners (event
handlers) that implement specific listener interfaces.
Core concepts:
 Event Source – The component that triggers an event (e.g., JButton, JTextField)
 Event Object – Encapsulates information about the event
(e.g., ActionEvent, MouseEvent, KeyEvent)
 Listener Interface – Defines methods that must be implemented to handle events
(e.g., ActionListener, MouseListener)
Common event types and their listeners:
Typical
Event Type Listener Interface Methods
Components

JButton, JMenuItem, J
Action ActionListener actionPerformed(ActionEvent)
TextField (Enter key)

mouseClicked, mousePressed, m
Mouse MouseListener ouseReleased, mouseEntered, mo Any component
useExited

Mouse MouseMotionListe
mouseDragged, mouseMoved Any component
Motion ner

keyPressed, keyReleased, keyTyp Any component


Key KeyListener
ed (focus required)

JCheckBox, JRadioBu
Item ItemListener itemStateChanged(ItemEvent)
tton, JComboBox

Focus FocusListener focusGained, focusLost Any component

insertUpdate, removeUpdate, cha JTextField, JTextArea


Document DocumentListener
ngedUpdate (text changes)

windowOpened, windowClosing,
Window WindowListener JFrame, JDialog
windowClosed, etc.

componentResized, componentM
Componen
ComponentListener oved, componentShown, compon Any component
t
entHidden
Five ways to implement event handling (from simplest to most advanced):
1. Lambda Expressions (Java 8+) – Best for simple actions:
java
JButton button = new JButton("Click");
[Link](e -> [Link]("Button clicked"));
2. Anonymous Inner Classes – Good for one-off handlers:
java
JButton button = new JButton("Click");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked");
}
});
3. Method References – Clean for predefined methods:
java
JButton button = new JButton("Click");
[Link](this::handleButtonClick);
private void handleButtonClick(ActionEvent e) {
[Link]("Button clicked");
}
4. Separate Listener Class – Reusable across components:
java
class ButtonClickHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) [Link]();
[Link]([Link]() + " clicked");
}
}

// Usage
JButton btn1 = new JButton("Save");
JButton btn2 = new JButton("Delete");
ButtonClickHandler handler = new ButtonClickHandler();
[Link](handler);
[Link](handler);
5. Adapter Classes – For multi-method listeners (e.g., MouseListener) :
java
JPanel panel = new JPanel();
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Clicked at: " + [Link]() + ", " + [Link]());
}

@Override
public void mouseEntered(MouseEvent e) {
[Link](Color.LIGHT_GRAY);
}
});
Complete example with multiple event types:
java
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class EventHandlingDemo extends JFrame {


private JLabel statusLabel;
private JTextField textField;
private JCheckBox checkBox;

public EventHandlingDemo() {
setTitle("Event Handling Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Status bar
statusLabel = new JLabel("Ready", [Link]);
[Link]([Link]());

// Control panel
JPanel controlPanel = new JPanel(new GridLayout(4, 1, 10, 10));
[Link]([Link](10, 10, 10, 10));

// 1. Action event (button)


JButton actionButton = new JButton("Click Me");
[Link](e ->
[Link]("Button clicked: " + new [Link]())
);

// 2. Focus event (text field)


textField = new JTextField(20);
[Link](new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
[Link]("Text field focused");
[Link]([Link]);
}
@Override
public void focusLost(FocusEvent e) {
[Link]("Text field lost focus");
[Link]([Link]);
}
});

// 3. Item event (checkbox)


checkBox = new JCheckBox("Enable feature");
[Link](e ->
[Link]("Checkbox is " + ([Link]() ==
[Link] ? "checked" : "unchecked"))
);

// 4. Key event (text field)


[Link](new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
[Link]("Typed: " + [Link]());
}
});

// 5. Mouse event on the whole window


addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]([Link]("Mouse clicked at (%d, %d)", [Link](),
[Link]()));
}
});

[Link](new JLabel("Action:"));
[Link](actionButton);
[Link](new JLabel("Focus & Key:"));
[Link](textField);
[Link](new JLabel("Item:"));
[Link](checkBox);

add(controlPanel, [Link]);
add(statusLabel, [Link]);

pack();
setSize(400, 300);
setLocationRelativeTo(null);
}

public static void main(String[] args) {


[Link](() -> new EventHandlingDemo().setVisible(true));
}
}
Important event handling best practices:
 Never perform long-running operations in event handlers – they freeze the UI.
Use SwingWorker for background tasks.
 Use [Link]() to update GUI components from background
threads.
 Consume events when appropriate – [Link]() prevents further processing.
 Remove listeners when no longer needed to prevent memory leaks.
7. Layout Managers (Brief Overview)
Layout managers automatically position and size components within containers. Never use
absolute positioning (setLayout(null)) – it breaks across platforms.
Layout Manager Description Best for

FlowLayout Left-to-right, wraps Toolbars, button panels

BorderLayout (JFrame NORTH, SOUTH, EAST, WEST,


Main window layout
default) CENTER

Calculator, form with uniform


GridLayout Equal-sized grid
rows

Complex forms, professional


GridBagLayout Powerful grid with variable sizes
layouts

BoxLayout Horizontal or vertical stack Linear arrangement


Layout Manager Description Best for

Stack of panels, one visible at a


CardLayout Wizards, tabbed interfaces
time
Example combining layouts:
java
JFrame frame = new JFrame();
[Link](new BorderLayout());

JPanel topPanel = new JPanel(new FlowLayout([Link]));


[Link](new JButton("Save"));
[Link](new JButton("Cancel"));
[Link](topPanel, [Link]);

JPanel centerPanel = new JPanel(new GridBagLayout());


// ... add form fields
[Link](centerPanel, [Link]);
Summary: When to Use What
 Use Swing for all new desktop applications – it's modern, feature-rich, and cross-
platform.
 Use AWT only for – very simple applets (deprecated), or when you need absolute
minimal footprint (rare).
 Use JOptionPane for standard dialogs – message, confirmation, input.
 Use JDialog for custom complex dialogs – modal or non-modal.
 Use lambda expressions for simple event handlers – cleanest code.
 Use adapter classes for multi-method listeners – avoid empty method
implementations.
 Always run Swing on the EDT – [Link]().

You might also like