4

这是我想要做的,其中一个类是包含所有 JButtons 的 JFrame,我想要另一个类来监听对 JFrame 类所做的操作。请看下面的代码:

public class Frame extends JFrame{
    //all the jcomponents in here

}

public class listener implements ActionListener{
    //listen to the actions made by the Frame class

}

谢谢你的时间。

4

3 回答 3

6

只需将侦听器的新实例添加到您想要侦听的任何组件中。任何实现的类ActionListener都可以作为侦听器添加到您的组件中。

public class Frame extends JFrame {
    JButton testButton;

    public Frame() {
        testButton = new JButton();
        testButton.addActionListener(new listener());

        this.add(testButton);
    }
}
于 2012-08-09T17:18:44.323 回答
3

1.您可以使用Inner Class, 或Anonymous Inner Class来解决这个问题......

例如:

内部类

public class Test{

 Button b = new Button();


 class MyListener implements ActionListener{

       public void actionPerformed(ActionEvent e) {

                    // Do whatever you want to do on the button click.
      } 

   }
}

例如:

匿名内部类

public class Test{

     Button b = new Button();

     b.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

                        // Do whatever you want to do on the button click.
          } 


   });

    }
于 2012-08-09T17:35:36.953 回答
1

如果您想要一个相同的实例listener来监听框架中的所有按钮,则必须使 actionPerformed 方法收集所有点击并根据命令进行委托:

public class listener extends ActionListener{
    public void actionPerformed(ActionEvent e){
        String command = e.getActionCommand();
        if (command.equals("foo")) {
            handleFoo(e);
        } else if (command.equals("bar")) {
            handleBar(e);
        }
    }

    private void handleFoo(ActionEvent e) {...}
    private void handleBar(ActionEvent e) {...}
}

在 Java 7 中这将变得更容易,您可以在其中切换字符串!Text按钮单击的ActionCommand将是 的-JButton属性,除非您另外设置

于 2012-08-09T19:28:34.293 回答