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 JButton
s 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());
}
}
精彩评论