我最近在做一個編程任務,要求我們在代碼中實現一個由UML圖指定的程序。在某一點上,圖表指定我必須創建一個匿名JButton,它顯示一個計數(從一開始),並在每次點擊時遞減。 JButton和它的ActionListener都必須是匿名的。實現ActionListener的Java匿名類?
我想出了以下解決方案:
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()
,但是有沒有另一種更優雅的方式來達到相同的結果?
看一下你現在@Tim – Insane 2016-07-09 07:59:43