Reputation: 5723
I have this code:
public class Window extends JFrame {
public Window(){
...
JButton button = new JButton("OK");
getContentPane().add(button);
ButtonHandler handler = new ButtonHandler();
button.addActionListener(handler);
...
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
if (event.getSource() == button){ // <--- "button can not be resolved"
System.out.println("Hello");
}
}
}
I'm getting that error in Eclipse. I just made a (simplified) example found in a book, dont know what can be wrong. Knowledge eye required! :)
Upvotes: 1
Views: 520
Reputation: 205805
The button
object is not visible in class ButtonHandler
; it's local to the Window
constructor. You can make it a field in Window
or find out what command was intended from the ActionEvent
. See the tutorial for more.
Addendum: for example
if ("OK".equals(event.getActionCommand())) { ...
Upvotes: 3
Reputation: 39760
There is away of making the button handler aware of which button is responding to, but this will prevent you from using the same object.
make a new constructor that takes the button object is a key
//...
ButtonHandler handler = new ButtonHandler(button);
//...
and then
private class ButtonHandler implements ActionListener {
private JButton button;
ButtonHandler( JButton button) { this.button = button; }
public void actionPerformed(ActionEvent event){
if (event.getSource() == button){ // <--- "button can not be resolved"
System.out.println("Hello");
}
}
Upvotes: 1
Reputation: 8677
Avoid having your ActionListener action dependent on what button was pressed. If you have different actions for different buttons then define a seperate ActionListener for each action.
That way your listener doesn't need to check what button was pressed.
public void actionPerformed(ActionEvent event){
System.out.println("Hello");
}
Upvotes: 2