Cristol.GdM
Cristol.GdM

Reputation: 534

Repainting a frame/label through a button

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();
    }
}

}

Upvotes: 0

Views: 206

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your assumption is that since the JButton's text was created with the Score variable (which should start with a lower-case letter and be named "score" to comply with approved Java naming convention), that changing scores value with change the JButton's text's value, but that just won't happen. You need to set the text of the JButton yourself via setText to change its text.

Upvotes: 2

xthexder
xthexder

Reputation: 1565

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.

Upvotes: 2

Related Questions