Reputation: 46
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
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
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:
setBounds
) as this will lead to frustration, grief and poor GUI's. Use layout managersUpvotes: 1