I was recently doing a programming assignment that required us to implement in code a program specified by a UML diagram. At one point, the diagram specified that I had to create an anonymous JButton that displayed a count (starting at one) and decremented each time it was clicked. The JButton and its ActionListener both had to be anonymous.
I came up with the following solution:
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);
}
This adds an anonymous JButton, then adds another (inner) anonymous ActionListener to handle events and update the button's text as necessary. Is there a better solution? I'm pretty sure I can't declare an anonymous JButton implements ActionListener ()
, but is there another more elegant way to achieve the same result?