最近我在做一个编程作业,需要根据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来处理事件并根据需要更新按钮的文本。是否有更好的解决方案?我相当确定我不能声明一个实现ActionListener的匿名JButton,但是是否有另一种更优雅的方法来实现相同的结果?