How to change a JLabel dynamically
The issue is that you are creating a new, different JLabel that is not show in the panel.
do
public void calculate(){
pressed++;
this.label1.setText("You have pressed button " + pressed + "times.");
}
You only call calculate()
when the button start
is clicked. So you can move that method into the ActionListener for the button. And by calling setText
on the JLabel, you don't have to call repaint
. Normally you don't have to call repaint
in Swing. E.g. change your code to something like this instead:
final JLabel label1 = new JLabel("You have pressed button " + pressed + "times.");
private JButton start = new JButton(new AbstractAction("Click To Start!") {
public void actionPerformed(ActionEvent e) {
pressed++;
label1.setText("You have pressed button " + pressed + "times.");
}
});
Change label1 = new JLabel("You have pressed button " + pressed + "times.");
to label1.setText("You have pressed button " + pressed + "times.");