简体   繁体   中英

Java ActionListener class can't find variables.

I have three classes, one main class, one GUI class which uses awt+swing to make a basic window with 4 buttons.

//BEGIN ADD ACTION LISTENERS
handle_events event_handler=new handle_events();
home_b.addActionListener(event_handler);
my_account_b.addActionListener(event_handler);
my_history_b.addActionListener(event_handler);
exit_b.addActionListener(event_handler);
//END ADD ACTION LISTENERS

My handle_events class looks like this:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class handle_events implements ActionListener
{
    public handle_events(){}

    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource==home_b) {do stuff;}
            //etc               
    }


}
//END EVENT HANDLER CLASS

The problem is that home_b can't be found by the ActionListener class, regardless of what I do. Thanks for all your help.

Because the handle_events has no reference to it. You can either add reference to that in the constructor:

class handle_events implements ActionListener
{
    private Object home_b;

    public handle_events(Object home_b){
         this.home_b = home_b;
    }

    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource==home_b) {do stuff;}
            //etc               
    }
}

(where you replace Object with whatever type home_b is supposed to be), or you can convert the handle_events class to a nested one in the class where you have the code which initializes those action listeners.

And BTW unless you have a very good reason to do so, you should adhere to common coding styles and declare class names with uppercase letters at the beginning and not using underscores: HandleEvents .

Because your handle_events class is in another scope it will never find the home_b variable. That's the reason a lot people use Anonymous Listener classes for event handlers.

JButton button = new JButton((new AbstractAction("name of button") {
public void actionPerformed(ActionEvent e) {
    //do stuff here
    }
}));

The biggest benefit to doing it this way is that you don't need to check to see who is the source, you know it right then and there in the code what that handler needs to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM