Maverick Davidson
Maverick Davidson

Reputation: 46

Updating a JLabel with a Static Integer

So I'm new to Java, I took a class in highschool last year and want to try and make my own little 2d game that Im working on. I have a stats.java that is filled with all the variables I want stored, such as cash, name, level, etc. Right now Im trying to add Cash to my Cash JLabel using a button.

JButton btnAddCash = new JButton("ADD 10,000");
btnAddCash.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        stats.cash = (stats.cash + 5000);
    }
});

JLabel lblCash = new JLabel("Cash: " +stats.cash);
lblCash.setForeground(Color.WHITE);
lblCash.setBounds(10, 649, 162, 14);
contentPane.add(lblCash);
lblCash.setFont(new Font("AirbusMCDUa", Font.BOLD, 15));
JButton debugBtn = new JButton("");

Any help would be awesome!

Upvotes: 0

Views: 102

Answers (2)

0ddlyoko
0ddlyoko

Reputation: 330

You just have to update your JLabel !

JLabel lblCash = new JLabel("Cash: " + stats.cash);

lblCash.setForeground(Color.WHITE);
lblCash.setBounds(10, 649, 162, 14);
lblCash.setFont(new Font("AirbusMCDUa", Font.BOLD, 15));
contentPane.add(lblCash);

JButton btnAddCash = new JButton("ADD 10,000");
btnAddCash.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        stats.cash += 5000;                        // += is faster
        lblCash.setText("Cash: " + stats.cash);    // <-- Here
    }
});
contentPane.add(btnAddCash);                       // <-- Here

JButton debugBtn = new JButton("");

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Your problem is here at (A) and (B)

JButton btnAddCash = new JButton("ADD 10,000");
btnAddCash.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        stats.cash = (stats.cash + 5000); //     (A)
    }
});

JLabel lblCash = new JLabel("Cash: " +stats.cash); //     (B)

Understand that when you create the JLabel it holds the present value of the cash field and does not hold a reference to the field itself. This is important since updating the cash field will have no effect on the JLabel's text. You must explicitly change that text:

btnAddCash.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        stats.cash = (stats.cash + 5000);    
        lblCash.setText("Cash: " +stats.cash);  // ****** update the text
    }
});

Other issues:

  • Again, avoid static unless you have a good reason for using this
  • Look up the Model-View-Controller design pattern and study it. This type of structure is what you will eventually want to use.
  • Avoid absolute positioning of components (null layouts and setBounds) as this will lead to frustration, grief and poor GUI's. Use layout managers
  • Consider learning JavaFX instead of Swing since JavaFX is being supported actively by Oracle while Swing is not.

Upvotes: 1

Related Questions