📜  java JButton onClick - Java (1)

📅  最后修改于: 2023-12-03 15:15:56.424000             🧑  作者: Mango

Java JButton onClick

JButton is a class in Java swing package which is used to create a button. The onClick event in Java swing is used to perform some action when a button is clicked. This guide will explain how to create a button and add the onClick event listener to the button in Java.

Creating a JButton

To create a JButton in Java, we first need to import the necessary libraries:

import javax.swing.*;

We can then create a JButton using the following code:

JButton button = new JButton("Click Me!");

This will create a JButton with the text "Click Me!".

Adding an onClick Event Listener

To add an onClick event listener to the JButton, we can use the addActionListener() method. We must first create a class that implements the ActionListener interface, which requires us to implement the actionPerformed() method. This method is where we will write the code to be executed when the button is clicked.

public class ButtonClickListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // code to be executed on button click
    }       
}

We can then add an instance of this class as a listener to the JButton:

ButtonClickListener listener = new ButtonClickListener();
button.addActionListener(listener);

Now, when the button is clicked, the actionPerformed() method in the ButtonClickListener class will be executed.

Full Example

Here is a full example of creating a JButton and adding an onClick event listener:

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Example");
        JPanel panel = new JPanel();
        JButton button = new JButton("Click Me!");

        panel.add(button);
        frame.add(panel);
        frame.setSize(300, 300);
        frame.setVisible(true);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Button Clicked");
            }
        });
    }
}

In this example, a JFrame with a JPanel is created and a button is added to the panel. An onClick event listener is added directly to the button using an anonymous inner class, which displays a message dialog when the button is clicked.

Conclusion

Adding an onClick event listener to a JButton in Java is simple and straightforward. By creating a class that implements the ActionListener interface, we can write the code to be executed on button click in the actionPerformed() method. We can then add an instance of this class as a listener to the JButton using the addActionListener() method.