Event Handling in Java
1. What is Event Handling?
✔ Event handling in Java refers to managing user interactions, such as clicking a button, pressing a key, or moving the mouse.
✔ It is widely used in Graphical User Interface (GUI) programming with Swing, AWT, and JavaFX.
2. Java Event Handling Mechanism
Event handling follows the "Event Delegation Model", which has three main components:
3. Event Handling Using ActionListener
(Button Click Example)
✔ The ActionListener
interface is used to handle button clicks.
Example: Handling Button Clicks
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener {
Button btn;
MyFrame() {
btn = new Button("Click Me");
btn.setBounds(100, 100, 80, 30);
btn.addActionListener(this); // Register event
add(btn);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
public static void main(String[] args) {
new MyFrame();
}
}
✔ btn.addActionListener(this)
registers the button with the event listener.
✔ actionPerformed()
is executed when the button is clicked.
Output:
Button Clicked!
4. Event Classes (java.awt.event
)
Java provides different event classes to handle various user actions:
5. Handling Mouse Events (MouseListener
)
✔ The MouseListener
interface is used to detect mouse clicks and movements.
Example: Mouse Click Detection
import java.awt.*;
import java.awt.event.*;
class MouseEventDemo extends Frame implements MouseListener {
Label label;
MouseEventDemo() {
label = new Label("Click anywhere!");
label.setBounds(50, 50, 200, 30);
add(label);
addMouseListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
}
✔ addMouseListener(this)
registers the window to detect mouse events.
✔ mouseClicked(MouseEvent e)
runs when the mouse is clicked.
6. Handling Key Events (KeyListener
)
✔ The KeyListener
interface is used to detect keyboard key presses.
Example: Detecting Key Presses
import java.awt.*;
import java.awt.event.*;
class KeyEventDemo extends Frame implements KeyListener {
Label label;
KeyEventDemo() {
label = new Label("Press any key...");
label.setBounds(50, 50, 200, 30);
add(label);
addKeyListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyEventDemo();
}
}
✔ addKeyListener(this)
registers the window to listen for key events.
✔ keyPressed(KeyEvent e)
runs when a key is pressed.
7. Using WindowListener
(Window Close Event)
✔ The WindowListener
interface is used to handle window closing events.
Example: Closing a Window Properly
import java.awt.*;
import java.awt.event.*;
class WindowEventDemo extends Frame implements WindowListener {
WindowEventDemo() {
addWindowListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing...");
dispose(); // Close window properly
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public static void main(String[] args) {
new WindowEventDemo();
}
}
✔ addWindowListener(this)
registers the window with a WindowListener
.
✔ windowClosing(WindowEvent e)
closes the window safely.
8. Event Handling with Anonymous Classes
✔ We can use anonymous classes instead of implements ActionListener
.
Example: Button Click with Anonymous Class
import java.awt.*;
import java.awt.event.*;
class AnonymousEventDemo {
public static void main(String[] args) {
Frame f = new Frame("Anonymous Listener");
Button btn = new Button("Click Me");
btn.setBounds(100, 100, 80, 30);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
f.add(btn);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}
✔ Shorter code using an anonymous class.
✔ No need for implements ActionListener
.
9. Summary
✔ Event handling is used for GUI interactions in Java.
✔ Event sources (e.g., Buttons) generate events.
✔ Listeners (ActionListener
, MouseListener
, etc.) handle events.
✔ addActionListener()
, addMouseListener()
, etc., register event handlers.
✔ Anonymous classes can simplify event handling.
Event Types in Java
Java supports multiple types of events, mainly classified into GUI events, input events, and application-specific events. These events are handled using event listeners in the java.awt.event and javax.swing.event packages.
1. Categories of Events in Java
Java events are broadly classified into:
2. Common Event Classes and Their Uses
(i) ActionEvent (Button Clicks, Menu Selections)
✔ Triggered when a button is clicked, or a menu item is selected.
✔ Implemented using the ActionListener interface.
Example: Handling Button Clicks
import java.awt.*;
import java.awt.event.*;
class ActionEventDemo extends Frame implements ActionListener {
Button btn;
ActionEventDemo() {
btn = new Button("Click Me");
btn.setBounds(100, 100, 100, 30);
btn.addActionListener(this);
add(btn);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
public static void main(String[] args) {
new ActionEventDemo();
}
}
✔ actionPerformed(ActionEvent e) is executed when the button is clicked.
(ii) MouseEvent (Mouse Actions: Click, Move, Enter, Exit)
✔ Handles mouse interactions, such as clicks, movements, and button presses.
✔ Implemented using the MouseListener and MouseMotionListener interfaces.
Example: Detecting Mouse Clicks
import java.awt.*;
import java.awt.event.*;
class MouseEventDemo extends Frame implements MouseListener {
Label label;
MouseEventDemo() {
label = new Label("Click anywhere!");
label.setBounds(50, 50, 200, 30);
add(label);
addMouseListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
}
✔ mouseClicked(MouseEvent e) detects mouse clicks and prints coordinates.
(iii) KeyEvent (Keyboard Key Presses)
✔Handles keyboard input, such as key presses and releases.
✔ Implemented using the KeyListener interface.
Example: Detecting Key Presses
import java.awt.*;
import java.awt.event.*;
class KeyEventDemo extends Frame implements KeyListener {
Label label;
KeyEventDemo() {
label = new Label("Press any key...");
label.setBounds(50, 50, 200, 30);
add(label);
addKeyListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyEventDemo();
}
}
✔ keyPressed(KeyEvent e) detects when a key is pressed.
(iv) FocusEvent (Focus Gained/Lost)
✔ Detects when a component (e.g., text field) gains or loses focus.
✔ Implemented using the FocusListener interface.
Example: Detecting Focus Changes
import java.awt.*;
import java.awt.event.*;
class FocusEventDemo extends Frame implements FocusListener {
TextField tf1, tf2;
FocusEventDemo() {
tf1 = new TextField("Enter here");
tf1.setBounds(50, 50, 150, 30);
tf1.addFocusListener(this);
tf2 = new TextField("Click here next");
tf2.setBounds(50, 100, 150, 30);
tf2.addFocusListener(this);
add(tf1); add(tf2);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void focusGained(FocusEvent e) {
TextField t = (TextField) e.getSource();
t.setBackground(Color.YELLOW);
}
public void focusLost(FocusEvent e) {
TextField t = (TextField) e.getSource();
t.setBackground(Color.WHITE);
}
public static void main(String[] args) {
new FocusEventDemo();
}
}
✔ focusGained(FocusEvent e) highlights the focused field.
(v) WindowEvent (Window Actions: Close, Minimize, Open)
✔ Detects window actions, such as closing or minimizing a window.
✔ Implemented using the WindowListener interface.
Example: Closing a Window Properly
import java.awt.*;
import java.awt.event.*;
class WindowEventDemo extends Frame implements WindowListener {
WindowEventDemo() {
addWindowListener(this);
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing...");
dispose(); // Close window safely
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public static void main(String[] args) {
new WindowEventDemo();
}
}
✔ windowClosing(WindowEvent e) closes the window safely.
3. Summary
✔ ActionEvent → Button clicks, menu selections.
✔ MouseEvent → Mouse clicks, movements.
✔ KeyEvent → Keyboard key presses.
✔ FocusEvent → Focus gained/lost in text fields.
✔ WindowEvent → Window opened, closed, minimized.
Mouse and Key Events in Java
Mouse and keyboard events in Java are used to detect mouse clicks, movements, and key presses. These events are handled using MouseListener, MouseMotionListener, and KeyListener interfaces from the java.awt.event package.
1. Mouse Events (MouseListener and MouseMotionListener)
Mouse Event Types:
Example: Detecting Mouse Clicks and Movements
import java.awt.*;
import java.awt.event.*;
class MouseEventDemo extends Frame implements MouseListener, MouseMotionListener {
Label label;
MouseEventDemo() {
label = new Label("Click or Move the Mouse!");
label.setBounds(50, 50, 250, 30);
add(label);
addMouseListener(this);
addMouseMotionListener(this);
setSize(400, 300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered the Frame");
}
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited the Frame");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged to X: " + e.getX() + ", Y: " + e.getY());
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved to X: " + e.getX() + ", Y: " + e.getY());
}
public static void main(String[] args) {
new MouseEventDemo();
}
}
✔ mouseClicked(MouseEvent e) → Detects mouse click location.
✔ mouseMoved(MouseEvent e) → Detects real-time mouse movement.
✔ mouseDragged(MouseEvent e) → Detects when the mouse is moved while clicked.
2. Key Events (KeyListener)
Key Event Types:
Example: Detecting Key Presses
import java.awt.*;
import java.awt.event.*;
class KeyEventDemo extends Frame implements KeyListener {
Label label;
KeyEventDemo() {
label = new Label("Press any key...");
label.setBounds(50, 50, 200, 30);
add(label);
addKeyListener(this);
setSize(400, 200);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
label.setText("Key Released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyEventDemo();
}
}
✔ keyPressed(KeyEvent e) → Detects when a key is pressed.
✔ keyReleased(KeyEvent e) → Detects when a key is released.
3. Combined Mouse and Key Events Example
✔ This example detects both mouse and key interactions in a single frame.
import java.awt.*;
import java.awt.event.*;
class MouseKeyEventDemo extends Frame implements MouseListener, KeyListener {
Label label;
MouseKeyEventDemo() {
label = new Label("Interact with the Frame!");
label.setBounds(50, 50, 250, 30);
add(label);
addMouseListener(this);
addKeyListener(this);
setSize(400, 300);
setLayout(null);
setVisible(true);
}
// Mouse Events
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered the Frame");
}
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited the Frame");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
// Key Events
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new MouseKeyEventDemo();
}
}
✔ mouseClicked() detects mouse clicks.
✔ keyPressed() detects key presses.
4. Summary
✔ Mouse Events (MouseListener & MouseMotionListener)Detect mouse clicks, movement, and dragging.
✔ Key Events (KeyListener)Detect key presses and releases.
✔ Multiple Event Handling
Basics of GUI in Java
Graphical User Interface (GUI) in Java is created using libraries like AWT (Abstract Window Toolkit) and Swing. These provide components like buttons, text fields, and windows to build interactive applications.
---
1. AWT vs. Swing
For modern applications, Swing is preferred over AWT.
---
2. Creating a Basic Swing GUI
A simple Java Swing GUI consists of:
JFrame → The main window.
JButton → A clickable button.
JLabel → A text label.
JTextField → An input field.
Example: Basic Swing Window
import javax.swing.*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("My First GUI"); // Create a window
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close on exit
JLabel label = new JLabel("Hello, Swing!", SwingConstants.CENTER);
frame.add(label); // Add label to the frame
frame.setVisible(true); // Show the window
}
}
✔ JFrame creates a window.
✔ JLabel displays text.
✔ setVisible(true) makes the window appear.
---
3. Adding Buttons and Actions
We use JButton and ActionListener to handle button clicks.
Example: Button Click Event
import javax.swing.*;
import java.awt.event.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JButton button = new JButton("Click Me");
button.setBounds(150, 80, 100, 30);
frame.add(button);
JLabel label = new JLabel("Button not clicked yet");
label.setBounds(120, 40, 200, 30);
frame.add(label);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});
frame.setVisible(true);
}
}
✔ JButton creates a clickable button.
✔ addActionListener() detects clicks.
✔ Updates JLabel on button press.
---
4. Adding Text Fields and Input Handling
A JTextField allows user input, and we can retrieve its value on a button click.
Example: Getting Text Input
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Field Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JTextField textField = new JTextField();
textField.setBounds(50, 50, 200, 30);
frame.add(textField);
JButton button = new JButton("Submit");
button.setBounds(260, 50, 100, 30);
frame.add(button);
JLabel label = new JLabel("Enter text and press submit");
label.setBounds(50, 100, 300, 30);
frame.add(label);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("You entered: " + textField.getText());
}
});
frame.setVisible(true);
}
}
✔ JTextField gets user input.
✔ getText() retrieves entered text.
---
5. Layout Managers
Java provides different layouts for arranging components: | Layout | Description | |-----------|----------------| | FlowLayout | Arranges components in a row | | BorderLayout | Divides container into five regions (N, S, E, W, Center) | | GridLayout | Arranges components in a grid | | BoxLayout | Arranges components in a single row or column |
Example: Using FlowLayout
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); // Set FlowLayout
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setVisible(true);
}
}
✔ setLayout(new FlowLayout()) arranges buttons in a row.
---
6. GUI Event Handling
Example: Checkbox Selection
import javax.swing.*;
import java.awt.event.*;
public class CheckboxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Checkbox Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JCheckBox checkBox = new JCheckBox("Accept Terms & Conditions");
checkBox.setBounds(50, 50, 200, 30);
frame.add(checkBox);
JLabel label = new JLabel("Unchecked");
label.setBounds(50, 100, 200, 30);
frame.add(label);
checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText(checkBox.isSelected() ? "Checked" : "Unchecked");
}
});
frame.setVisible(true);
}
}
✔ JCheckBox creates a checkbox.
✔ ItemListener detects selection changes.
---
7. Swing vs JavaFX
JavaFX is a newer alternative to Swing with modern UI features like animations and CSS styling. However, Swing is still widely used for desktop applications.
---
8. Summary
✔ Swing Components: JFrame, JButton, JLabel, JTextField, JCheckBox.
✔ Event Handling: Uses ActionListe
ner, KeyListener, MouseListener.
✔ Layouts: FlowLayout, BorderLayout, GridLayout.
✔ Modern Alternative: JavaFX provides richer UI features.
Would you like examples for menus, tables, or advanced components?
Panels in Java (JPanel - Swing & Panel - AWT)
A panel is a container that groups multiple components (buttons, labels, text fields) together. Java provides two types of panels:
Panel (AWT) → Part of java.awt (old GUI toolkit).
JPanel (Swing) → Part of javax.swing (modern GUI toolkit, preferred).
---
1. Creating a JPanel (Swing)
A JPanel is used within a JFrame to organize components.
Example: Simple JPanel
import javax.swing.*;
public class JPanelExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JPanel Example"); // Main window
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(); // Create panel
JLabel label = new JLabel("Hello, JPanel!");
JButton button = new JButton("Click Me");
panel.add(label); // Add components to panel
panel.add(button);
frame.add(panel); // Add panel to frame
frame.setVisible(true);
}
}
✔ JPanel acts as a container for JLabel and JButton.
✔ add(panel) adds the panel to the frame.
---
2. Using JPanel with Layouts
JPanels can use different layouts to arrange components.
Example: JPanel with GridLayout
import javax.swing.*;
import java.awt.*;
public class GridLayoutPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 2)); // 2x2 grid
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ new GridLayout(2,2) → Creates a 2x2 button grid.
---
3. Nested JPanels
You can nest multiple panels to organize components better.
Example: Nested Panels
import javax.swing.*;
import java.awt.*;
public class NestedPanelExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Nested JPanel Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Top Panel"));
JPanel centerPanel = new JPanel(new GridLayout(2, 2));
centerPanel.add(new JButton("1"));
centerPanel.add(new JButton("2"));
centerPanel.add(new JButton("3"));
centerPanel.add(new JButton("4"));
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(centerPanel, BorderLayout.CENTER);
frame.add(mainPanel);
frame.setVisible(true);
}
}
✔ topPanel → Holds a JLabel.
✔ centerPanel → Holds a 2x2 button grid.
---
4. JPanel with a Background Color
You can change the panel's background color using setBackground(Color).
Example: Colorful JPanel
import javax.swing.*;
import java.awt.*;
public class ColoredPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("Colored JPanel");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.CYAN); // Set background color
panel.add(new JLabel("This is a cyan panel"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ setBackground(Color.CYAN) sets the panel color.
---
5. JPanel with Borders
A JPanel can have a border for better visualization.
Example: JPanel with a Border
import javax.swing.*;
import javax.swing.border.*;
public class BorderedPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("Bordered JPanel");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("My Panel"));
panel.add(new JLabel("This panel has a border"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ BorderFactory.createTitledBorder("My Panel") adds a title border.
---
6. Summary
✔ JPanel is a container for organizing GUI components.
✔ Supports layouts (FlowLayout, Gri
dLayout, BorderLayout).
✔ Can be nested inside other JPanels.
✔ Can have background colors & borders.
Would you like an example of dynamic panel switching (CardLayout)?
Frames in Java (JFrame - Swing & Frame - AWT)
A Frame is a top-level container in Java that represents a window. There are two main types of frames:
Frame (AWT) → From java.awt, older and OS-dependent.
JFrame (Swing) → From javax.swing, modern and more flexible (preferred).
---
1. Creating a Simple JFrame
A JFrame is the main window where all GUI components (buttons, labels, panels) are added.
Example: Basic JFrame
import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My First JFrame"); // Create a window
frame.setSize(400, 300); // Set width & height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close on exit
frame.setVisible(true); // Display the frame
}
}
✔ JFrame creates the window.
✔ setSize(400, 300) sets the frame dimensions.
✔ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the app when the frame is closed.
✔ setVisible(true) makes the window appear.
---
2. Adding Components to JFrame
We can add buttons, labels, and other GUI elements inside the frame.
Example: JFrame with a Button and Label
import javax.swing.*;
public class FrameWithComponents {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // No default layout
JLabel label = new JLabel("Click the button:");
label.setBounds(50, 50, 150, 30);
frame.add(label);
JButton button = new JButton("Click Me");
button.setBounds(50, 100, 120, 30);
frame.add(button);
frame.setVisible(true);
}
}
✔ setLayout(null) → Allows manual positioning of components using setBounds(x, y, width, height).
✔ add(label) → Adds a JLabel to the frame.
✔ add(button) → Adds a JButton.
---
3. Handling Window Events
We can handle frame close, minimize, and maximize events using WindowListener.
Example: Detecting Window Close Event
import javax.swing.*;
import java.awt.event.*;
public class WindowEventExample extends JFrame implements WindowListener {
WindowEventExample() {
setTitle("Window Event Example");
setSize(400, 300);
addWindowListener(this);
setVisible(true);
}
public void windowOpened(WindowEvent e) { System.out.println("Window Opened"); }
public void windowClosing(WindowEvent e) { System.out.println("Window Closing"); }
public void windowClosed(WindowEvent e) { System.out.println("Window Closed"); }
public void windowIconified(WindowEvent e) { System.out.println("Window Minimized"); }
public void windowDeiconified(WindowEvent e) { System.out.println("Window Restored"); }
public void windowActivated(WindowEvent e) { System.out.println("Window Activated"); }
public void windowDeactivated(WindowEvent e) { System.out.println("Window Deactivated"); }
public static void main(String[] args) {
new WindowEventExample();
}
}
✔ addWindowListener(this) → Detects window actions.
✔ windowClosing() → Runs when the frame is closing.
---
4. Using JFrame with Panels
JFrames can contain JPanels to organize components better.
Example: JFrame with a JPanel
import javax.swing.*;
import java.awt.*;
public class FrameWithPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame with JPanel");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY); // Set background color
panel.add(new JLabel("Welcome to the panel"));
panel.add(new JButton("Click Me"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ JPanel organizes components inside JFrame.
✔ setBackground(Color.LIGHT_GRAY) changes panel color.
---
5. Full-Screen JFrame
To make the frame cover the entire screen, use setExtendedState(JFrame.MAXIMIZED_BOTH).
Example: Full-Screen Window
import javax.swing.*;
public class FullScreenFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Full Screen Frame");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // Maximize the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
✔ setExtendedState(JFrame.MAXIMIZED_BOTH) makes the frame full screen.
---
6. JFrame with a Menu Bar
Swing allows adding menus inside a frame using JMenuBar.
Example: JFrame with a Menu
import javax.swing.*;
public class MenuFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame with Menu");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
}
✔ JMenuBar creates a top menu bar.
✔ JMenu adds a menu ("File").
✔ JMenuItem adds menu items ("Open", "Exit").
---
7. Summary
✔ JFrame → Main window container.
✔ Adding Components → Use add() to insert buttons, labels, text fields.
✔ Events → Use
WindowListener to detect window events.
✔ Panels → Use JPanel to organize components.
✔ Menus → Use JMenuBar, JMenu, JMenuItem.
Would you like an example of JTabbedPane (multiple tabs in a JFrame)?
Layout Managers in Java (Swing & AWT)
Layout managers in Java control how components are arranged inside a JFrame or JPanel. Instead of manually setting positions with setBounds(), we use layout managers for automatic resizing and better UI organization.
---
1. Types of Layout Managers
---
2. FlowLayout (Default for JPanel)
Arranges components in a row, left to right, like words in a sentence.
Example: FlowLayout
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout()); // Default is center-aligned
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ FlowLayout() arranges buttons in a row.
✔ Components wrap to the next line if the frame is too small.
---
3. BorderLayout (Default for JFrame)
Divides the container into five regions:
NORTH (Top)
SOUTH (Bottom)
EAST (Right)
WEST (Left)
CENTER (Middle, expands automatically)
Example: BorderLayout
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JButton("NORTH"), BorderLayout.NORTH);
frame.add(new JButton("SOUTH"), BorderLayout.SOUTH);
frame.add(new JButton("EAST"), BorderLayout.EAST);
frame.add(new JButton("WEST"), BorderLayout.WEST);
frame.add(new JButton("CENTER"), BorderLayout.CENTER);
frame.setVisible(true);
}
}
✔ Center expands when the window resizes.
✔ Best for layouts with toolbars and side panels.
4. GridLayout (Table-Like Structure)
Arranges components in equal-sized rows and columns.
Example: GridLayout (3x2)
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
frame.setVisible(true);
}
}
✔ GridLayout(rows, cols) arranges components in a fixed grid.
✔ All cells are of equal size.
5. BoxLayout (Aligns Components in a Line)
BoxLayout(panel, BoxLayout.Y_AXIS) → Vertical layout
BoxLayout(panel, BoxLayout.X_AXIS) → Horizontal layout
Example: BoxLayout (Vertical Alignment)
import javax.swing.*;
import java.awt.*;
public class BoxLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Vertical alignment
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ Useful for vertical menus and forms.
6. GridBagLayout (Advanced Flexible Grid)
Allows different cell sizes and custom alignments.
Example: GridBagLayout
import javax.swing.*;
import java.awt.*;
public class GridBagExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0; gbc.gridy = 0; // Position (0,0)
panel.add(new JButton("Button 1"), gbc);
gbc.gridx = 1; gbc.gridy = 0; // Position (1,0)
panel.add(new JButton("Button 2"), gbc);
gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; // Span 2 columns
panel.add(new JButton("Wide Button"), gbc);
frame.add(panel);
frame.setVisible(true);
}
}
✔ Allows fine-tuned control over positioning.
✔ Can span multiple rows or columns.
7. CardLayout (Switchable Panels)
Useful for tabs, wizards, and dynamic screens.
Example: CardLayout with Buttons
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new CardLayout());
JPanel card1 = new JPanel();
card1.add(new JLabel("This is Card 1"));
JPanel card2 = new JPanel();
card2.add(new JLabel("This is Card 2"));
panel.add(card1, "Card 1");
panel.add(card2, "Card 2");
CardLayout cl = (CardLayout) panel.getLayout();
JButton switchButton = new JButton("Switch Card");
switchButton.addActionListener(e -> cl.next(panel));
frame.add(panel, BorderLayout.CENTER);
frame.add(switchButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
✔ CardLayout allows switching between multiple panels.
✔ Useful for forms, slides, and wizards.
FlowLayout in Java
FlowLayout is the simplest layout manager in Java. It arranges components in a row, wrapping to the next line when needed. It is the default layout for JPanel.
1. Creating a FlowLayout
FlowLayout arranges components like text in a paragraph (left to right, top to bottom).
Example: FlowLayout with Buttons
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // Default alignment: CENTER
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
panel.add(new JButton("Button 5"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ Buttons align in a row (wrapping when needed).
✔ Default alignment: centered.
2. FlowLayout Constructor
FlowLayout()
FlowLayout(int align)
FlowLayout(int align, int hGap, int vGap)
3. Setting Alignment and Gaps
Example: Left-Aligned FlowLayout with Custom Gaps
import javax.swing.*;
import java.awt.*;
public class FlowLayoutCustom {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Custom");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 10)); // Left alignment, 20px horizontal gap, 10px vertical gap
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
panel.add(new JButton("Button 5"));
frame.add(panel);
frame.setVisible(true);
}
}
✔ FlowLayout.LEFT → Aligns components to the left.
✔ 20px horizontal gap and 10px vertical gap between components.
5. When to Use FlowLayout
✅ Good for:
✔ Small toolbars, buttons, or forms.
✔ Simple UIs where components naturally wrap.
❌ Avoid when:
✘ You need precise positioning → Use GridBagLayout.
✘ Components should resize equally → Use GridLayout.
BorderLayout in Java
BorderLayout is one of the most commonly used layout managers in Java. It divides a container into five regions:
NORTH (Top)
SOUTH (Bottom)
EAST (Right)
WEST (Left)
CENTER (Middle, expands automatically)
Default for: JFrame (if no layout is set explicitly).
1. Creating a BorderLayout
Example: BorderLayout with Buttons
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout()); // Setting BorderLayout explicitly
frame.add(new JButton("NORTH"), BorderLayout.NORTH);
frame.add(new JButton("SOUTH"), BorderLayout.SOUTH);
frame.add(new JButton("EAST"), BorderLayout.EAST);
frame.add(new JButton("WEST"), BorderLayout.WEST);
frame.add(new JButton("CENTER"), BorderLayout.CENTER);
frame.setVisible(true);
}
}
✔ NORTH and SOUTH → Span the full width of the frame.
✔ EAST and WEST → Adjust their height to match CENTER.
✔ CENTER → Expands automatically if other regions are empty.
2. BorderLayout Constructor
BorderLayout()
BorderLayout(int hGap, int vGap)
3. Customizing Gaps
Example: BorderLayout with Spacing
import javax.swing.*;
import java.awt.*;
public class BorderLayoutWithGaps {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout with Gaps");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout(10, 20)); // 10px horizontal, 20px vertical gap
frame.add(new JButton("NORTH"), BorderLayout.NORTH);
frame.add(new JButton("SOUTH"), BorderLayout.SOUTH);
frame.add(new JButton("EAST"), BorderLayout.EAST);
frame.add(new JButton("WEST"), BorderLayout.WEST);
frame.add(new JButton("CENTER"), BorderLayout.CENTER);
frame.setVisible(true);
}
}
✔ 10px horizontal gap and 20px vertical gap between components.
4. Mixing BorderLayout with Other Layouts
Often, we use JPanel with a different layout inside a BorderLayout.
Example: Nested Layouts (BorderLayout + FlowLayout)
import javax.swing.*;
import java.awt.*;
public class NestedLayouts {
public static void main(String[] args) {
JFrame frame = new JFrame("Nested Layouts");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel topPanel = new JPanel(new FlowLayout()); // Panel with FlowLayout
topPanel.add(new JButton("Button 1"));
topPanel.add(new JButton("Button 2"));
topPanel.add(new JButton("Button 3"));
frame.add(topPanel, BorderLayout.NORTH); // Adding panel to NORTH
frame.add(new JButton("CENTER"), BorderLayout.CENTER);
frame.setVisible(true);
}
}
✔ Panel in NORTH uses FlowLayout (row of buttons).
✔ CENTER button expands automatical
5. BorderLayout vs. Other La
6. When to Use BorderLayout
✅ Best for:
✔ Designing the main window layout.
✔ Creating UI structures with toolbars (NORTH, WEST).
✔ Automatically resizing the CENTER component.
❌ Avoid when:
✘ You need precise positioning → Use GridBagLayout.
✘ All components must be the same size → Use GridLayout.
GridLayout in Java
GridLayout is used to arrange components in a grid (rows and columns), where each cell has equal size. It automatically resizes components to fit the grid.
Key Features:
✔ All components are equally sized
✔ Rows are filled left to right
✔ No gaps by default (but can be set)
1. Creating a GridLayout
Example: 3 Rows × 2 Columns
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
frame.setVisible(true);
}
}
✔ Buttons arranged in a 3×2 grid.
✔ All buttons have equal width & height.
2. GridLayout Constructor
GridLayout(int rows, int cols)
GridLayout(int rows, int cols, int hGap, int vGap)
3. Adding Spacing Between Components
Example: GridLayout with Gaps
import javax.swing.*;
import java.awt.*;
public class GridLayoutWithGaps {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout with Gaps");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(2, 3, 10, 10)); // 2 rows, 3 columns, 10px gaps
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
frame.setVisible(true);
}
}
✔ 10px horizontal & vertical gaps between buttons.
4. Dynamic Grid (Flexible Rows or Columns)
If rows = 0, the number of rows adjusts dynamically.
If columns = 0, the number of columns adjusts dynamically.
Example: Dynamic Column Grid (1 Row, Unlimited Columns)
import javax.swing.*;
import java.awt.*;
public class DynamicGrid {
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Grid");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(1, 0)); // 1 row, unlimited columns
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
frame.setVisible(true);
}
}
✔ All buttons appear in one row (auto-adjusts columns).
5. Mixing GridLayout with Other Layouts
We can use JPanel with GridLayout inside a JFrame with another layout.
Example: GridLayout Inside a Panel
import javax.swing.*;
import java.awt.*;
public class NestedGridLayout {
public static void main(String[] args) {
JFrame frame = new JFrame("Nested Layouts");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel gridPanel = new JPanel(new GridLayout(2, 2)); // 2x2 Grid
gridPanel.add(new JButton("1"));
gridPanel.add(new JButton("2"));
gridPanel.add(new JButton("3"));
gridPanel.add(new JButton("4"));
frame.add(gridPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
✔ Grid (2×2) is placed inside CENTER of BorderLayout.
6. GridLayout vs. Other Layouts
7. When to Use GridLayout
✅ Best for:
✔ Simple tables or button layouts.
✔ Arranging components symmetrically.
✔ Calculator-like interfaces.
❌ Avoid when:
✘ Components ne
ed different sizes → Use GridBagLayout.
✘ Components should wrap naturally → Use FlowLayout.
GUI Components in Java: Buttons
In Java, GUI components such as buttons are used to interact with users. JButton is one of the most commonly used components. It represents a button that can trigger events when clicked.
1. JButton in Java
Creating a JButton
To create a button, you simply instantiate a JButton object and add it to a container like JFrame or JPanel.
Example: Basic JButton
import javax.swing.*;
import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!"); // Creating a button with text
frame.add(button);
frame.setVisible(true);
}
}
✔ Button displays text ("Click Me!") in the window.
2. Adding Action Listeners to JButton
To make the button functional, you add an ActionListener to listen for click events.
Example: JButton with ActionListener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonActionListenerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("ActionListener Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
// Adding ActionListener to the button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setVisible(true);
}
}
✔ ActionListener is triggered when the button is clicked, displaying a message.
3. Button Customization
You can change the text, font, color, and even icon on a button.
Example: Customized JButton
import javax.swing.*;
import java.awt.*;
public class CustomButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Custom JButton Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Custom Button");
button.setFont(new Font("Arial", Font.BOLD, 16)); // Custom font
button.setBackground(Color.CYAN); // Button background color
button.setForeground(Color.WHITE); // Button text color
frame.add(button);
frame.setVisible(true);
}
}
✔ Font → Arial, bold, size 16.
✔ Background color → Cyan.
✔ Text color → White.
4. Using Icons in JButton
You can also add icons to buttons using ImageIcon.
Example: JButton with Icon
import javax.swing.*;
import java.awt.*;
public class IconButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Icon Button Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creating an icon for the button
ImageIcon icon = new ImageIcon("path_to_icon.png");
JButton button = new JButton("Click Me!", icon);
frame.add(button);
frame.setVisible(true);
}
}
✔ Icon added next to the text on the button.
✔ You need to specify the path to an image for the ImageIcon.
5. Button Types in Java
Java provides various types of buttons for different purposes:
1. JButton – Regular button for actions.
2. JCheckBox – For boolean options (checked/unchecked).
3. JRadioButton – For a group of mutually exclusive options.
4. JToggleButton – A button that stays pressed after being clicked.
5. JButton with mnemonic – Buttons with keyboard shortcuts.
Example: JButton with Mnemonic
import javax.swing.*;
public class MnemonicButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Mnemonic Button Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Press &B");
button.setMnemonic(KeyEvent.VK_B); // Alt + B as a shortcut
frame.add(button);
frame.setVisible(true);
}
}
✔ Mnemonic → Press Alt + B to activate the button.
6. Disabling and Enabling Buttons
You can disable a button, making it unclickable, or re-enable it based on certain conditions.
Example: Disable/Enable JButton
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisableEnableButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Disable/Enable Button Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
button.setEnabled(false); // Initially disable the button
// Enable the button when the frame is clicked
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
button.setEnabled(true); // Enable button after frame click
}
});
frame.add(button);
frame.setVisible(true);
}
}
✔ Initially, the button is disabled.
✔ After a frame click, the button is enabled.
7. Button Groups (Radio Buttons)
JRadioButton is used when you want users to select only one option from a set of choices (radio button behavior). All radio buttons in a group are mutually exclusive.
Example: JRadioButton with Button Group
import javax.swing.*;
import java.awt.*;
public class RadioButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Radio Button Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton option1 = new JRadioButton("Option 1");
JRadioButton option2 = new JRadioButton("Option 2");
JRadioButton option3 = new JRadioButton("Option 3");
// Group the radio buttons to make them mutually exclusive
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
JPanel panel = new JPanel();
panel.add(option1);
panel.add(option2);
panel.add(option3);
frame.add(panel);
frame.setVisible(
true);
}
}
✔ ButtonGroup ensures only one radio button is selected at a time.
GUI Components in Java: Checkboxes, Bars, Sliders, Windows, Menus, Dialog Boxes
Java provides a variety of GUI components for creating interactive applications. Here's an overview of key components such as checkboxes, progress bars, sliders, windows, menus, and dialog boxes.
1. JCheckBox (Checkbox)
Checkboxes are used for selecting multiple options from a set of choices.
Example: JCheckBox
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox checkBox1 = new JCheckBox("Option 1");
JCheckBox checkBox2 = new JCheckBox("Option 2");
// Adding ActionListener to the checkboxes
checkBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkBox1.isSelected()) {
JOptionPane.showMessageDialog(frame, "Option 1 Selected");
} else {
JOptionPane.showMessageDialog(frame, "Option 1 Deselected");
}
}
});
JPanel panel = new JPanel();
panel.add(checkBox1);
panel.add(checkBox2);
frame.add(panel);
frame.setVisible(true);
}
}
✔ JCheckBox allows the user to select or deselect options.
✔ ActionListener responds when a checkbox is selected/deselected.
2. JProgressBar (Progress Bar)
A progress bar is used to show the progress of a task.
Example: JProgressBar
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class ProgressBarExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JProgressBar Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar progressBar = new JProgressBar(0, 100); // Progress from 0 to 100
progressBar.setValue(50); // Set initial value (50%)
progressBar.setStringPainted(true); // Show percentage text
frame.add(progressBar);
frame.setVisible(true);
}
}
✔ Progress bar visually shows the completion of a task.
✔ String painted to display percentage of completion.
3. JSlider (Slider)
A slider allows users to select a value from a range by sliding a knob.
Example: JSlider
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class JSliderExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JSlider Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50); // Range from 0 to 100, initial value 50
slider.setMajorTickSpacing(10); // Major tick marks at intervals of 10
slider.setPaintTicks(true); // Display tick marks
slider.setPaintLabels(true); // Display labels for tick marks
// Add change listener to track slider value changes
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JOptionPane.showMessageDialog(frame, "Slider Value: " + slider.getValue());
}
});
frame.add(slider);
frame.setVisible(true);
}
}
✔ JSlider is used for selecting numeric values visually.
✔ ChangeListener listens for value changes and updates accordingly.
4. JFrame (Window)
A JFrame is a top-level container used to create a window.
Example: Basic JFrame (Window)
import javax.swing.*;
public class JFrameExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, World!");
frame.add(label);
frame.setVisible(true);
}
}
✔ JFrame creates the main application window.
✔ JLabel is added inside the frame to display text.
5. JMenu (Menu)
Menus are used to create lists of commands or options that can be selected. The JMenu component is used to create menus.
Example: JMenu (Menu)
import javax.swing.*;
public class JMenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JMenu Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creating a menu bar
JMenuBar menuBar = new JMenuBar();
// Creating a menu
JMenu fileMenu = new JMenu("File");
// Adding menu items
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");
// Adding ActionListener to Exit menu item
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(openItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu); // Adding menu to menu bar
frame.setJMenuBar(menuBar); // Setting the menu bar for the frame
frame.setVisible(true);
}
}
✔ JMenuBar holds multiple JMenu components.
✔ JMenuItem represents options within a menu.
✔ ActionListener exits the application when Exit is selected.
6. JDialog (Dialog Box)
A JDialog is used to display a modal or non-modal dialog box for user input or notifications.
Example: Simple JDialog
import javax.swing.*;
public class JDialogExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JDialog Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton openDialogButton = new JButton("Open Dialog");
// Action to open dialog on button click
openDialogButton.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "This is a dialog box!", "Dialog Box", JOptionPane.INFORMATION_MESSAGE);
});
frame.add(openDialogButton);
frame.setVisible(true);
}
}
✔ JDialog creates a simple popup dialog to show
a message.
✔ JOptionPane.showMessageDialog creates a simple modal dialog box.
Applet in Java and Its Lifecycle
In Java, an applet is a small application designed to be embedded within a web page and executed in a web browser. Applets were commonly used in the past for interactive applications like animations or games, but are now mostly outdated with the advent of modern web technologies like JavaScript, HTML5, and CSS.
Despite their decline in use, it's useful to understand how applets work and how their lifecycle is managed in Java.
1. What is an Applet?
An applet is a Java program that can be embedded in a web page and executed in a web browser. It requires the Java Plugin in the browser to run, and applets are executed within a JApplet class (which extends Applet in older versions of Java).
Applets typically have a user interface (UI) and interact with the user or respond to events.
Applets can be executed in the context of a web page, meaning they can interact with other web content.
2. Applet Life Cycle
An applet's lifecycle is defined by several methods that the Java Virtual Machine (JVM) calls during different stages of the applet's existence.
Stages of the Applet Life cycle
1. Initialization (init())
2. Starting (start())
3. Painting (paint())
4. Stopping (stop())
5. Destroying (destroy())
Lifecycle Methods:
1. init() - Initialization
This method is called once when the applet is first loaded.
Used for initializing the applet's resources, like setting up the user interface or reading data.
public void init() {
// Initialize applet
System.out.println("Applet initialized.");
}
2. start() - Starting
After init(), the start() method is called when the applet is ready to be displayed.
This is where you can start animations, threads, or timers.
It’s also called when the applet is brought to the foreground after being temporarily stopped.
public void start() {
// Start any animation or thread
System.out.println("Applet started.");
}
3. paint() - Painting
This method is called whenever the applet needs to update its display. For example, when the applet is resized or when a repaint is triggered by the system.
paint() is used for rendering graphics on the applet window.
public void paint(Graphics g) {
// Code to draw on the applet window
g.drawString("Hello, Applet!", 50, 50);
}
4. stop() - Stopping
This method is called when the applet is no longer visible or when the browser window is minimized.
Used to pause any ongoing processes like animations or threads.
public void stop() {
// Stop any ongoing tasks, such as animations or threads
System.out.println("Applet stopped.");
}
5. destroy() - Destroying
This method is called when the applet is about to be destroyed (when the page is unloaded or the browser is closed).
It’s used for cleaning up any resources like closing files, stopping network connections, or stopping threads.
public void destroy() {
// Cleanup resources before applet is destroyed
System.out.println("Applet destroyed.");
}
3. Example of an Applet
Here’s an example of an applet with basic lifecycle methods (init(), start(), stop(), and paint()):
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
@Override
public void init() {
// Initialize the applet
System.out.println("Applet Initialized.");
}
@Override
public void start() {
// Start applet activities (e.g., animations)
System.out.println("Applet Started.");
}
@Override
public void paint(Graphics g) {
// Painting the applet window (output on screen)
g.drawString("Hello, Applet!", 50, 50);
}
@Override
public void stop() {
// Stop any ongoing tasks
System.out.println("Applet Stopped.");
}
@Override
public void destroy() {
// Cleanup before destruction
System.out.println("Applet Destroyed.");
}
}
This applet would display "Hello, Applet!" in the window when loaded and print lifecycle stages to the console.
4. Loading an Applet in a Web Page
To display an applet in a web page, you use the <applet> tag (deprecated, and no longer recommended). However, modern browsers have phased out support for the <applet> tag.
Example of HTML Tag for an Applet
<html>
<body>
<applet code="SimpleApplet.class" width="300" height="200">
</applet>
</body>
</html>
code attribute: Specifies the applet class.
width and height attributes: Define the size of the applet’s
5. Applet vs. Application
6. Applet Deprecation
Deprecated since Java 9: Applets have been deprecated and are no longer supported in modern browsers (e.g., Chrome, Firefox, etc.), which no longer support Java Plugins.
Java 9+: With the removal of the Java Plugin, applets are no longer viable in most modern application
Summary of Applet Life Cycle:
✨init(): Initialize resources.
✨start(): Start any animations or tasks.
✨paint(Graphics g): Draw or update the display.
✨stop(): Pause tasks when the applet is not visible.
✨destroy(): Clean up resources before the applet is destroyed.
Introduction to Swing in Java
Swing is a GUI (Graphical User Interface) toolkit in Java used to create rich, interactive desktop applications. It is part of the Java Foundation Classes (JFC), which provides a set of APIs for building graphical user interfaces. Swing is built on top of the Abstract Window Toolkit (AWT) but offers more features and flexibility, making it more suitable for modern Java GUI development.
Swing components are lightweight, meaning they do not rely on the underlying operating system's windowing system but instead are drawn by Java itself, providing a consistent look across different platforms.
1. Key Features of Swing
💫Lightweight Components: Swing components are not tied to the native OS look and feel, which makes them more flexible and customizable.
💫Pluggable Look and Feel (PLAF): Swing allows you to change the appearance of your app with different "look-and-feel" themes, such as Windows, Metal, or others.
💫Event Handling: Swing uses listeners and events to respond to user actions.
💫Advanced Components: Swing offers a range of complex components like tables (JTable), trees (JTree), and text panes (JTextPane).
💫Rich Customization: Swing components can be customized with colors, fonts, and other properties.
2. Swing vs. AWT
💫While AWT provides basic GUI components, Swing enhances and extends the capabilities of AWT by offering:
💫Better control over UI design and more complex components.
💫Platform-independent look and feel (AWT components rely on native system components).
💫Swing components are fully customizable, unlike AWT components, which use the system’s appearance
3. Swing Components
Swing provides a vast number of components that can be used to create the user interface:
Basic Swing Components:
👉JFrame: The main window that contains other GUI components (like buttons, labels, etc.).
👉JButton: A clickable button that triggers an action.
👉JLabel: Displays text or images.
👉JTextField: A single-line text input field.
👉JTextArea: A multi-line text input field.
👉JPanel: A container for organizing other components.
👉JComboBox: A drop-down menu for selecting from a list of items.
👉JCheckBox: A checkbox for selecting or unselecting options.
👉JRadioButton: A button that is part of a group, where only one button in the group can be selected at a time.
👉JList: A list of items from which users can select.
👉JTable: A table for displaying and editing data in rows and columns.
4. Structure of a Simple Swing Application
Here’s a basic structure of a Swing-based application:
import javax.swing.*;
import java.awt.event.*;
public class SimpleSwingApp {
public static void main(String[] args) {
// Create a JFrame (main window)
JFrame frame = new JFrame("Swing Application");
// Create a JButton (button to interact with)
JButton button = new JButton("Click Me");
// Add an ActionListener to handle button click
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button clicked!");
}
});
// Add the button to the frame (window)
frame.add(button);
// Set frame properties
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Explanation:
💫JFrame: The main window.
💫JButton: A clickable button that shows a message when clicked.
💫ActionListener: Used to handle the event of clicking the button.
💫setSize(): Sets the window size.
💫setVisible(): Makes the window visible.
5. Layout Managers in Swing
💫Swing uses layout managers to organize components in a container. Some common layout managers are:
💫FlowLayout: Components are placed in a row, and when space is filled, they wrap to the next line.
💫BorderLayout: Divides the container into five regions: North, South, East, West, and Center.
💫GridLayout: Divides the container into a grid of rows and columns.
💫BoxLayout: Arranges components in a single row or column.
💫GridBagLayout: Provides fine-grained control over component positioning and resizing.
Example: Using Layout Manager
import javax.swing.*;
import java.awt.*;
public class LayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Layout Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set the layout manager to FlowLayout
fra
me.setLayout(new FlowLayout());
// Add some buttons to the frame
frame.add(new JButton("Button 1"));
frame.add(new JButton)
Exception Handling Mechanism in Java
In Java, exception handling is a powerful mechanism that helps developers manage errors and unexpected situations in a controlled and graceful manner. It ensures that the program can continue executing even when an error occurs, without abruptly terminating the program.
An exception is an event that disrupts the normal flow of the program's execution. For example, trying to access an array element that doesn't exist, dividing by zero, or attempting to open a file that doesn't exist are all cases that can cause exceptions.
1. What is an Exception?
An exception is an event or error condition that alters the normal flow of program execution. It occurs during runtime (i.e., while the program is running).
There are two main types of exceptions in Java:
1. Checked Exceptions: These are exceptions that are checked at compile-time. The compiler forces you to either handle or declare these exceptions. Examples include IOException, SQLException, etc.
2. Unchecked Exceptions: These are exceptions that are not checked at compile-time but rather at runtime. These are also called runtime exceptions and extend the RuntimeException class. Examples include ArithmeticException, NullPointerException, etc.
2. Exception Handling in Java
Java provides a robust mechanism to handle exceptions using five key components:
👉try block
👉catch block
👉finally block
👉throw statement
👉throws keyword
Basic Structure of Exception Handling
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handling the exception
} finally {
// Code that will always execute (optional)
}
Explanation of Components:
1. try block:
💫The code that might throw an exception is placed inside the try block.
💫If an exception occurs, the rest of the code inside the try block is skipped, and the program moves to the catch block.
2. catch block:
✨The catch block handles the exception. If an exception is thrown in the try block, the appropriate catch block catches the exception.
✨You can have multiple catch blocks to handle different types of exceptions.
3. finally block:
✨The finally block contains code that is always executed, whether or not an exception was thrown.
✨It is typically used for cleanup operations, such as closing files, network connections, or releasing resources.
4. throw statement:
✨The throw statement is used to explicitly throw an exception in your code.
✨You can throw both built-in and custom exceptions.
throw new Exception("An error occurred");
5. throws keyword:
✨The throws keyword is used in method signatures to declare that a method can throw one or more exceptions.
✨This is used for checked exceptions that need to be declared.
public void myMethod() throws IOException {
// Code that may throw IOException
}
3. Types of Exceptions
Checked Exceptions
These exceptions must be either handled or declared using the throws keyword.
Examples:
•IOException: Thrown when an I/O operation fails.
•SQLException: Thrown when there is a database-related issue.
Unchecked Exceptions
These exceptions are not required to be explicitly handled or declared. They are usually runtime exceptions.
Examples:
NullPointerException: Thrown when trying to access a null object reference.
ArithmeticException: Thrown for arithmetic errors, like division by zero.
4. Example: Basic Exception Handling
Example 1: Handling an ArithmeticException (Unchecked Exception)
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException: Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed!");
}
}
}
Example 2: Handling a FileNotFoundException (Checked Exception)
import java.io.*;
public class FileExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("non_existent_file.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
Explanation:
In the first example, we are dividing by zero, which triggers an ArithmeticException. This exception is caught, and an appropriate message is displayed.
In the second example, we are attempting to open a file that does not exist, which triggers a FileNotFoundException, a checked exception. The exception is caught, and a message is displayed.
5. Multi-Catch Block
Java 7 introduced the multi-catch block, which allows catching multiple exceptions in a single catch block.
try {
// Some code that might throw multiple exceptions
} catch (IOException | SQLException e) {
// Handle both IOException and SQLException
System.out.println("Error: " + e.getMessage());
}
6. Nested try-catch Blocks
You can also nest try-catch blocks within each other, allowing for more specific exception handling.
try {
try {
// Code that might throw an exception
} catch (IOException e) {
// Handle IOException
}
} catch (SQLException e) {
// Handle SQLException
}
7. Custom Exceptions
You can define your own exception classes by extending the Exception class.
Example: Creating a Custom Exception
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new MyException("This is a custom exception!");
} catch (MyException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
}
Explanation:
A custom exception class MyException is created by extending the Exception class.
The exception is thrown and caught, and the message is displayed.
8. Best Practices for Exception Handling
1. Catch specific exceptions first: Always catch the most specific exceptions before catching general ones. This avoids the problem of a generic Exception block catching all exceptions.
2. Don’t use exceptions for control flow: Exceptions should be used for error handling, not for normal control flow. Don’t use them as a regular program flow mechanism.
3. Log exceptions: It's good practice to log exception details (using Logger or printStackTrace()) to aid in debugging.
4. Clean up resources: Always use the finally block (or try-with-resources) to close files, database connections, or other resources.
5. Avoid empty catch blocks: Never catch exceptions and leave the catch block empty. Always handle or log the exception.
Summary
👉Exception handling in Java allows the graceful handling of runtime errors.
👉Java uses the try, catch, finally, throw, and throws mechanisms to handle exceptions.
👉Checked exceptions must be declared or handled, while unchecked exceptions (runtime exceptions) do not require explicit handling