Event Handling and Listeners - potatoscript/JavaSwing GitHub Wiki
⚡ Event Handling and Listeners in Java Swing ⚡
📝 What is Event Handling in Java Swing?
In Java Swing, Event Handling refers to the process of responding to user actions, such as clicks, typing, or mouse movement. These actions are called events, and Java provides a way to listen for these events and respond accordingly.
For instance, when a user clicks a button, an event is generated, and the program can handle that event by executing a specific action.
🎯 Key Concepts:
- Event: An object that encapsulates the details of a user interaction (like a mouse click or key press).
- Listener: A special interface that listens for events and defines what happens when an event occurs.
- Event Source: The component (such as a button or text field) that generates the event.
- Event Listener: A class or object that listens for and responds to the event generated by the event source.
📚 Types of Events in Java Swing
🖱️ Mouse Events:
- MouseListener: Used for handling mouse events like clicks, entering, and exiting components.
mousePressed()
,mouseReleased()
,mouseClicked()
,mouseEntered()
,mouseExited()
⌨️ Keyboard Events:
- KeyListener: Used for handling keyboard events like key presses and releases.
keyPressed()
,keyReleased()
,keyTyped()
🖱️ Action Events:
- ActionListener: Used for handling actions like button clicks or menu selections.
actionPerformed()
🔄 Window Events:
- WindowListener: Used for handling window events like opening, closing, and resizing windows.
windowOpened()
,windowClosing()
,windowClosed()
📚 Step 1: ActionListener and Button Click
📝 Example: Using ActionListener with a Button
In this example, we’ll create a simple JButton that, when clicked, displays a message in a JLabel.
import javax.swing.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("ActionListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
// Create a button
JButton button = new JButton("Click Me!");
button.setBounds(50, 50, 200, 40);
// Create a label
JLabel label = new JLabel("Message will appear here");
label.setBounds(50, 120, 200, 30);
// Add an ActionListener to the button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button was clicked!");
}
});
// Add components to the frame
frame.add(button);
frame.add(label);
// Show the frame
frame.setVisible(true);
}
}
🎨 Explanation:
- JButton: A button labeled "Click Me!" is created.
- JLabel: A label that initially displays "Message will appear here".
- ActionListener: The
addActionListener
method is used to listen for button clicks. When the button is clicked, theactionPerformed
method is triggered, changing the text of the label to "Button was clicked!".
👩🎨 Output:
- When the button is clicked, the label's text changes to "Button was clicked!".
📚 Step 2: MouseListener and Mouse Events
📝 Example: Using MouseListener to Track Mouse Events
In this example, we will create a JPanel and listen for mouse clicks, entry, and exit events.
import javax.swing.*;
import java.awt.event.*;
public class MouseListenerExample {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("MouseListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
// Create a panel to listen for mouse events
JPanel panel = new JPanel();
panel.setBounds(50, 50, 200, 100);
panel.setBackground(Color.CYAN);
// Add a MouseListener to the panel
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getPoint());
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered the panel");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited the panel");
}
});
// Add the panel to the frame
frame.add(panel);
// Show the frame
frame.setVisible(true);
}
}
🎨 Explanation:
- JPanel: A panel is created with a cyan background.
- MouseListener: The panel listens for mouse events. When the mouse is clicked, entered, or exited, the corresponding methods (
mouseClicked
,mouseEntered
, andmouseExited
) are triggered and print messages to the console.
👩🎨 Output:
- When the mouse clicks on the panel, it prints the click location.
- When the mouse enters or exits the panel, it prints appropriate messages to the console.
📚 Step 3: KeyListener and Keyboard Events
📝 Example: Using KeyListener to Track Key Presses
In this example, we’ll create a JTextField that listens for key presses and displays the pressed key in a JLabel.
import javax.swing.*;
import java.awt.event.*;
public class KeyListenerExample {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("KeyListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
// Create a text field
JTextField textField = new JTextField();
textField.setBounds(50, 50, 200, 30);
// Create a label
JLabel label = new JLabel("Pressed key will appear here");
label.setBounds(50, 100, 200, 30);
// Add a KeyListener to the text field
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
char key = e.getKeyChar();
label.setText("Key Pressed: " + key);
}
});
// Add components to the frame
frame.add(textField);
frame.add(label);
// Show the frame
frame.setVisible(true);
}
}
🎨 Explanation:
- JTextField: A text field is created where the user can type.
- JLabel: A label that will display the key pressed.
- KeyListener: The
addKeyListener
method is used to listen for key presses. ThekeyPressed
method is triggered when a key is pressed, and it updates the label with the key that was pressed.
👩🎨 Output:
- When the user types in the text field, the label updates to show the pressed key.
📚 Step 4: WindowListener and Window Events
📝 Example: Using WindowListener to Track Window Events
In this example, we’ll create a JFrame and listen for window events such as opening, closing, and resizing.
import javax.swing.*;
import java.awt.event.*;
public class WindowListenerExample {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("WindowListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Add a WindowListener
frame.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
System.out.println("Window opened!");
}
public void windowClosing(WindowEvent e) {
System.out.println("Window closing!");
}
});
// Show the frame
frame.setVisible(true);
}
}
🎨 Explanation:
- WindowListener: The
addWindowListener
method is used to listen for window events like opening or closing. ThewindowOpened
andwindowClosing
methods are triggered accordingly.
👩🎨 Output:
- When the window opens, it prints "Window opened!".
- When the window is about to close, it prints "Window closing!".