我是java的新手,所以请轻松一点。我正在尝试制作一个简单的游戏,每当你点击一个按钮,它就会向变量添加一个。一切正常,但我也试图将变量显示到我的JFrame。这就是麻烦来的地方,我点击按钮,它确实在我的变量中添加了一个(我将变量打印到控制台以确定),但JFrame没有更新变量。我还应该注意,当你第一次打开游戏时,它会打开一个允许你输入用户名的窗口,这是一个单独的类,它包含我的主要方法。这是我的第二个窗口的代码,有问题的那个:
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();
}
}
答案 0 :(得分:2)
它没有更新,因为您没有使用新的Component
金额更新任何pennies
。您的addMoney()
方法应该如下所示:
private void addMoney() {
pennies += moneyAddRate;
lblPennies.setText(String.format("You have %d pennies", pennies));
lblPennies.repaint();
}