Recently, I performed a programming assignment, which required us to implement the program specified in the UML diagram in the code. At some point, the diagram indicates that I had to create an anonymous JButton, which showed the score (starting with one) and decreased every time I clicked. JButton and its ActionListener should have been 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, and then adds another (internal) anonymous ActionListener to handle events, and updates the button text if necessary. Is there a better solution? I'm sure I can't declare anonymous JButton implements ActionListener (), but is there another elegant way to achieve the same result?