我是java的新手,所以放轻松。我正在尝试制作一个简单的游戏,每次单击按钮时都会向变量添加一个。一切正常,但我也在尝试将变量显示到我的 JFrame。这就是问题所在,我单击按钮,它确实向我的变量添加了一个(我将变量打印到控制台以确保)但 JFrame 没有更新变量。我还应该注意,当你第一次打开游戏时,它会打开一个允许你输入用户名的窗口,这是一个单独的类,其中包含我的 main 方法。这是我的第二个窗口的代码,即有问题的窗口:
import javax.swing.BorderFactory;
public class Game extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private String name;
public static int pennies = 0;
public static int dollars = 0;
public static int moneyAddRate = 1;
private JButton btnAddMoney = new JButton(new ImageIcon("C:\\Users\\Tanner\\git\\Money-Bags\\res\\coins\\oneCent.png"));
private Border emptyBorder = BorderFactory.createEmptyBorder();
public Game(String name) {
this.name = name;
createWindow();
}
private void createWindow() {
setTitle(name + "'s Economy");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAddMoney.setBounds(329, 244, 96, 96);
btnAddMoney.setBorder(emptyBorder);
contentPane.add(btnAddMoney);
btnAddMoney.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMoney();
}
});
JLabel lblPennies = new JLabel("You have " + pennies + " Pennies");
lblPennies.setBounds(10, 11, 152, 24);
contentPane.add(lblPennies);
JLabel lblDollars = new JLabel(dollars + " Dollars");
lblDollars.setBounds(10, 70, 152, 24);
contentPane.add(lblDollars);
JLabel lblAnd = new JLabel("&");
lblAnd.setBounds(10, 45, 61, 14);
contentPane.add(lblAnd);
setVisible(true);
}
private void addMoney() {
pennies += moneyAddRate;
System.out.println(pennies + " " + dollars);
contentPane.validate();
contentPane.repaint();
}
}