开发者

listeners on Java

开发者 https://www.devze.com 2023-02-23 02:27 出处:网络
Could anybody explain what\'s the problem with listeners in this code? I just started learning how listeners work and don\'t really realize how the ChangeListener works.

Could anybody explain what's the problem with listeners in this code?

I just started learning how listeners work and don't really realize how the ChangeListener works.

import java.awt.event.*;

class Button2 implements ChangeListener { //what's whong here

  public void changePerformed(ChangeEvent s) { //and here?
    System.out.println("Pressed the button " + s.getChangeCommand());
  }
}

Then I add two buttons.

.....
but1.addChangeListener(new Button2 ());
but2.addChangeListener(new Button2 ());
.....
开发者_JS百科


ChangeListener's required method is stateChanged, not changePerformed.

Edit: Also, as pointed out in a comment above, the ChangeListener I'm aware of is in javax.swing.event, not java.awt.event.


As zerocrats wrote ChangeListener's method is indeed stateChanged() and not changePerformed()

In addition, CahngeEvent has not method called getChangeCommand(). If you are using regular JButtons and just want to catch the click on th ebuttin, why not use the good old ActionListener?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
         System.out.println("Pressed the button " + e.getActionCommand());
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消