In this code I'm trying to make text update when the button is pressed, but it doesn't seem to update, even though the value of the variable does change on button press. Here is the code:
public class Test extends Applet implements ActionListener
{
Button Clicker;
int CurrentClicks = 0;
public void init()
{
this.setSize(600,400);
Button Clicker = new Button("Button 1");
add(Clicker);
Clicker.addActionListener(this);
}
public void paint (Graphics g)
{
g.drawString("Test",300,50);
g.drawString(String.valueOf(CurrentClicks), 300, 100);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println("Button 1 was pressed");
CurrentClicks++;
System.out.println("Current Clicks: "+CurrentClicks);
}
}
You need to refresh the container by calling repaint()
after modifying the instance variable.
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Button 1 was pressed");
CurrentClicks++;
System.out.println("Current Clicks: " + CurrentClicks);
repaint();
}
Also, please familiarize yourself with the Java naming conventions. For example, it is recommended to name your instance variable, CurrentClicks
, to currentClicks
.