tags:

views:

44

answers:

3

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! :)

+3  A: 

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())) { ...
trashgod
Think you meant it wasn't visible to class ButtonHandler
objects
Thanks! Answer amended.
trashgod
+2  A: 

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");
}
objects
+1  A: 

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");   

    }                  
}  
hhafez