2. Java GUI applications often require interaction
from the user. One of the most common user
interface elements used for this purpose is the
button. Buttons allow users to trigger actions
or events in the application. To handle these
button events effectively, Java provides the
ActionListener interface. In this discussion,
we'll explore how to use ActionListener with
buttons in Java GUI programming.
3. Understanding Action Listener
ActionListener is an interface in the
java.awt.event package.
It defines a single method,
actionPerformed(ActionEvent e), which is
invoked when an action occurs
4. Working with Buttons:
Buttons are created using the JButton class in
Swing or AWT.
They can display text, icons, or both, and they
can trigger events when clicked.
5. Implementing ActionListener:
To respond to button clicks, we need to
implement the ActionListener interface.
This involves creating a class that implements
ActionListener and providing logic inside the
actionPerformed() method.
6. Registering ActionListener with
Buttons:
After implementing ActionListener, we need to
register it with the button.
This is achieved by calling the
addActionListener() method on the button
object and passing an instance of the
ActionListener implementation.
7. import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button Clicked!");
}
}
public class ButtonClickExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");
button.addActionListener(new ButtonClickListener());
frame.setLayout(new FlowLayout());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}