实现ActionListener的Java匿名类? [英] Java anonymous class that implements ActionListener?

查看:107
本文介绍了实现ActionListener的Java匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近做了一个编程任务,要求我们在代码中实现一个由UML图指定的程序。有一次,该图指定我必须创建一个显示计数(从1开始)的匿名JButton,并在每次单击时递减。 JButton及其ActionListener都必须是匿名的。

I was recently doing a programming assignment that required us to implement in code a program specified by a UML diagram. At one point, the diagram specified that I had to create an anonymous JButton that displayed a count (starting at one) and decremented each time it was clicked. The JButton and its ActionListener both had to be anonymous.

我想出了以下解决方案:

I came up with the following solution:

public static void main(String[] args) {
  JFrame f = new JFrame("frame");
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.setSize(400, 400);

  f.getContentPane().add(new JButton() {

    public int counter;

    {
      this.counter = 1;
      this.setBackground(Color.ORANGE);
      this.setText(this.counter + "");

      this.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          counter --;
          setText(counter + "");
        }
      });

    }
  });

  f.setVisible(true);

}

这会添加一个匿名JButton,然后添加另一个(内部)匿名ActionListener来处理事件并根据需要更新按钮的文本。有更好的解决方案吗?我很确定我不能声明匿名 JButton实现了ActionListener(),但还有另一种更优雅的方法来实现相同的结果吗?

This adds an anonymous JButton, then adds another (inner) anonymous ActionListener to handle events and update the button's text as necessary. Is there a better solution? I'm pretty sure I can't declare an anonymous JButton implements ActionListener (), but is there another more elegant way to achieve the same result?

推荐答案

我通常会这样:

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

AbstractAction实现了ActionListener,因此它应该满足任务。

AbstractAction implements ActionListener so this should satisfy the task.

将这么多行代码压缩在一起可能是不好的做法,但是如果你习惯于阅读它,那么它可以非常优雅。

It can be bad practice to squish so many lines of code together, but if you're used to reading it then it can be quite elegant.

这篇关于实现ActionListener的Java匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆