Tim*_*Tim 5 java anonymous-class
我最近做了一个编程任务,要求我们在代码中实现一个由UML图指定的程序.有一次,该图指定我必须创建一个显示计数(从1开始)的匿名JButton,并在每次单击时递减.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);
}Run Code Online (Sandbox Code Playgroud)
这会添加一个匿名的JButton,然后添加另一个(内部)匿名ActionListener来处理事件并根据需要更新按钮的文本.有更好的解决方案吗?我很确定我不能宣布匿名JButton implements ActionListener (),但还有另一种更优雅的方法来实现相同的结果吗?
Cog*_*gsy 13
我通常会这样:
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("name of button") {
public void actionPerformed(ActionEvent e) {
//do stuff here
}
}));
Run Code Online (Sandbox Code Playgroud)
AbstractAction实现了ActionListener,因此它应该满足任务.
将这么多行代码压缩在一起可能是不好的做法,但如果你习惯于阅读它,那么它可以非常优雅.
| 归档时间: |
|
| 查看次数: |
34974 次 |
| 最近记录: |