gpt4 book ai didi

java - 更新我的 JFrame 时遇到问题

转载 作者:行者123 更新时间:2023-12-02 06:48:51 24 4
gpt4 key购买 nike

我对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();

}
}

最佳答案

它不会更新,因为您没有使用新的便士金额更新任何组件。您的 addMoney() 方法应如下所示:

private void addMoney() {
pennies += moneyAddRate;
lblPennies.setText(String.format("You have %d pennies", pennies));
lblPennies.repaint();
}

关于java - 更新我的 JFrame 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com