How to create an event for a button in Swing/Java

Asked

Viewed 481 times

0

Guys, I wanted to ask a favor, I wanted someone to show me how to create an event of a Jbutton, like, a q button when you click on it it opens another Jframe and closes the old one

use this code as an example

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

public class inicio{

    public void main(String[] args){
    JFrame frame = new JFrame();
    JButton bta = new JButton(“Clique aqui”);
    frame.setVisible(true);

    }
}

then the person clicks on the button "click here" and opens another Jframe and closes what was open, Obs: explain in the simplest way possible and avoid putting lines for the program to be more beautiful

1 answer

1

You can use the method addActionListener of your JButton to pass a functional interface to the button. Functional interface is an interface that implements a single method, this method will be invoked when the button is clicked.

A JButton expects an interface of the type ActionListener, which has the method called actionPerformed. You can implement this interface directly within the method call:

bta.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Seu código aqui
    }
});

Or, if you are using version 8 or higher of Java, you can reduce the amount of "Boilerplate" (repetitive code) using the syntax lambda.

bta.addActionListener(e -> {
    // Seu código aqui
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.