简体   繁体   English

Java ActionListener类找不到变量。

[英]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. 我有三个类,一个主类,一个GUI类,它使用awt + swing制作一个带有4个按钮的基本窗口。

//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: 我的handle_events类如下所示:

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. 问题是无论我做什么,ActionListener类都找不到home_b。 Thanks for all your help. 感谢你的帮助。

Because the handle_events has no reference to it. 因为handle_events没有引用。 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. (您可以使用home_b应该替换为Object的类型替换Object),也可以将handle_events类转换为该类中的嵌套类,在该类中您具有初始化这些动作侦听器的代码。

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 . 顺便说一句,除非您有充分的理由这样做,否则您应该坚持通用的编码样式,并在开头声明类名时使用大写字母,并且不要使用下划线: HandleEvents

Because your handle_events class is in another scope it will never find the home_b variable. 因为您的handle_events类在另一个作用域中,所以它将永远找不到home_b变量。 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. 这样做的最大好处是,您无需检查谁是源,就可以立即知道源代码,然后在代码中知道该处理程序需要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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