My problem seems to be quite simple, but I’ve been stuck on it for months; and now that it’s an assignment requirement, due two days from now, I have to give up and ask for help.
Basically, I have an int variable (called Score here), and a button that change the value of this variable; this works. But I also have a display of the present value of Score, and I want it to change to represent the value. However, it stays at 0, and doesn’t change at all.
I’ve made a piece of code as simple as possible (the actual project has around 15 files) which includes this problem: a button that displays the value of Score, and increments it. If someone could give me a solution on how to have the displayed value be the same as the value of the variable, that would be great 🙂
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main extends JFrame {
public static void main (String [] args) {
new Main();
}
public Main () {
setLocation (100, 100);
setSize (200, 200);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
content.add (new CrisButton ());
setVisible (true);
}
public class CrisButton extends JButton implements ActionListener{
public int Score;
CrisButton(){
setText(""+Score);
addActionListener(this);
}
public void actionPerformed(ActionEvent e){
System.out.println("Score="+Score);
Score=Score+2;
this.repaint();
}
}
}
You must use this.setText(“” + Score);
Score does not act as a pointer, so the value will never change.
You have to pass in a completely new string each time.