How to Add an ActionListener to JButton

-

How to Add an ActionListener to JButton

In a previous tutorial I showed you how to create and add a JButton to your JFrame in Java. Now I will show you how to add an ActionListener to your button so that you can handle when the button is clicked. In this tutorial we will create a pop up when the button is clicked.

Adding ActionListener to Handle Button Clicks

To make the button interactive, you need to listen for user clicks by adding an ActionListener to the button. When the button is clicked, an event is triggered, and the listener performs an action.

Example with ActionListener:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Main {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("JButton Example");

// Create a new JButton with a label
JButton button = new JButton("Click Me!");

// Add an ActionListener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Display a message when the button is clicked
JOptionPane.showMessageDialog(frame, "Button was clicked!");
}
});

// Set JButton size
button.setBounds(50, 70, 200, 20);

// Set the Layout to null
frame.setLayout(null);

// Add the button to the frame
frame.add(button);

// Set the size of the frame
frame.setSize(300, 200);

// Set the default close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make the frame visible
frame.setVisible(true);
}
}

In this example:

  • The ActionListener listens for the button click event.
  • When the button is clicked, a message box appears with the message “Button was clicked!”.

Conclusion

Creating a JButton in a JFrame is a straightforward process. First, create the button and add it to the frame. Then, handle the button click using an ActionListener to trigger actions. This allows you to build interactive GUI applications in Java.

You can further customize the button’s appearance, functionality, and behavior based on your application’s needs.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent comments