Search code examples
javalisteners

Object can not be resolved


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


Solution

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