私は最近、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);
}
これにより、匿名のJButtonが追加され、次に別の(内部の)匿名のActionListenerが追加されて、イベントが処理され、必要に応じてボタンのテキストが更新されます。より良い解決策はありますか?匿名を宣言することはできないと確信していますがJButton implements ActionListener ()
、同じ結果を達成するためのよりエレガントな方法は他にありますか?