我最近在做一个编程任务,要求我们在代码中实现一个由 UML 图指定的程序。有一次,该图指定我必须创建一个匿名 JButton,它显示一个计数(从 1 开始)并在每次单击时递减。JButton 及其 ActionListener 都必须是匿名的。
我想出了以下解决方案:
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 implements ActionListener ()
,但是还有另一种更优雅的方式来实现相同的结果吗?