简体   繁体   中英

Action Listener is not working when I press a Button

I got this code but when I run it the actionListener is not working.

Code

public class MenuPrincipal extends javax.swing.JFrame implements ActionListener {

public MenuPrincipal() {
    initComponents();
    this.setVisible(true);
    this.setLocationRelativeTo(null);
    this.addListener();
    this.jButton1 = new JButton();
    this.jButton2 = new JButton();
}

public static void main(String args[]) {
    new MenuPrincipal();
}

private void addListener() {   
    this.jButton1.addActionListener(this);
    this.jButton2.addActionListener(this);

    JOptionPane.showMessageDialog(null, "Activado");
}

@Override
public void actionPerformed(ActionEvent event) {
    if(event.getSource().equals(this.JButton1){
        // do something
    }

    if(event.getSource().equals(this.JButton2){
        // do something
    }
}

}

I'm using Netbeans to make the interface, thus I'm not pasting here the generated code.

You should write something in the method of the handler:

@Override
public void actionPerformed(ActionEvent event) {
   System.out.println("button pressed!");
}

and your class should implement the ActionListener interface

Alternatively you can use the java8 lambdas:

btn.addActionListener(e -> {System.out.println("button pressed!)});

remove this 2 lines from the constructor

this.jButton1 = new JButton();
this.jButton2 = new JButton();

Since addLsiteners method didnt throw any exception, that means you have already instantiated those JButtons. if you re instantiated then those fields will have the reference to different instances than the instance you added the action listener .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM