2

我在一个程序中有一个主类,它启动另一个处理所有 GUI 内容的类。在 GUI 中,我有一个需要附加 ActionListener 的按钮。

唯一的问题是,要执行的代码需要驻留在主类中。

当在别处单击按钮时,如何让 ActionPerformed() 方法在主类中执行?

4

3 回答 3

2

使您的控制器(“主”类)实现 ActionListener 接口,然后将引用传递给视图类:

public class View extends JFrame {
  public View(final ActionListener listener) {
   JButton button = new JButton("click me");
   button.addActionListener(listener);
   button.setActionCommand("do_stuff");

   getContentPane().add(button);

   pack();
   setVisible(true);
  }
 }

 public class Control implements ActionListener {

  public Control() {
   new View(this);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("do_stuff")) {
    // respond to button click
   }
  }
 }

也可以使用Actions来完成,但在您希望一段代码响应多个按钮的情况下,这更有用。

于 2010-03-09T04:34:14.687 回答
2

Implement an anonymous inner class as ActionListener on the button, then call the method on your main class. This creates less dependencies and avoids the tag & switch style programming that implementing the ActionListener interface on a main class tends to promote.

In either case it will create a cycle in your dependency graph: the main class will know about the button and the button will need to call the main class. This might not be a good idea since it will make it hard to compose things in any other way. But without further information it is hard to judge the situation or recommend anything concrete.

于 2010-03-09T04:59:30.633 回答
0

在主类中实现 ActionListener 并将主类实例添加为 GUI 按钮上的侦听器。

于 2010-03-09T03:58:21.090 回答