我最近做了一个编程任务,要求我们在代码中实现一个由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 (),但是有没有其他更优雅的方法来实现同样的结果呢?
发布于 2009-05-21 10:59:12
它非常难看,但您可以使用ActionListener方法和一个匿名类执行以下操作:
f.getContentPane().add(new JButton(new AbstractAction("name of button") {
private int counter = 0;
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setText(Integer.toString(counter--));
}
}) {
{
setText("1");
}
});为了更容易访问计数器,您可以将它移到类的顶层,并从调用setText的两个位置访问它。
https://stackoverflow.com/questions/891380
复制相似问题