【问题标题】:Unable to add actionlistener from another class [duplicate]无法从另一个类添加动作监听器[重复]
【发布时间】:2013-10-01 19:40:40
【问题描述】:

似乎我完全不明白这些东西是如何工作的......我有一个扩展 JPanel 并实现 Actionlistener 的类,然后我想将它添加到扩展 JFrame 的类中......我不能让它工作.....

public class testPanel extends JFrame implements ActionListener{
JButton someBtn;

public testPanel(JButton someBtn){
    this.someBtn = someBtn;
    add(someBtn);
    someBtn.addActionListener(this);

}

@Override
public void actionPerformed(ActionEvent e){
    if(e.getSource() == someBtn)
        System.out.println("this worked");
}

}

二级文件

public class JavaApplication3 extends JFrame{

/**
 * @param args the command line arguments
 */
JButton button;

public JavaApplication3(){
    super("blah");
    JFrame p = new testPanel(button);
    add(p);
    pack();
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    // TODO code application logic here
    new JavaApplication3();
}
}

【问题讨论】:

  • 你还没有初始化按钮实例变量...
  • 通常你会想要包含你得到的实际错误。
  • 你的例子不能工作,这两个类都是从 JFrame 扩展而来的

标签: java swing actionlistener


【解决方案1】:

testPanel 中的这一行肯定会抛出异常:

add(someBtn);

由于引用 someBtn 为空...

您从未在JavaApplication3 类中初始化button 实例变量,bzut 在testPanel 类的构造函数中使用了该变量。

但是,您希望得到此流程的逆向:

  1. testPanel 类中创建按钮
  2. 如果您想从 JavaApplication3 类中获取引用 - 您需要 testPanel 类中的 getter

例子:

public class testPanel extends JFrame implements ActionListener{
    JButton someBtn; //consider using private

    public testPanel(){
        this.someBtn = new JButton(); //add correct constructor here
        add(someBtn);
        someBtn.addActionListener(this);
    }

    public JButton getSomeBtn() {
        reeturn someBtn;
    }
//... rest comes here
}



public class JavaApplication3 extends JFrame{

    JButton button;

    public JavaApplication3(){
        super("blah");
        JFrame p = new testPanel();
        button  = p.getSomeBtn(); //this is the important line
        add(p);
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    //... rest comes here    
}

旁注:使用 Java 命名约定:类名以大写字母开头...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多