今天我开始学习Java而且我被困在这里,我不知道如何使用按钮刷新面板。这是我的代码:
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.*;
public class App {
public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0;
private static void GenerateStatus(){
Random randomGenerator = new Random();
STR = randomGenerator.nextInt(50);
aPower = randomGenerator.nextInt(50);
sPower = randomGenerator.nextInt(50);
INT = randomGenerator.nextInt(50);
STA = randomGenerator.nextInt(50);
DEF = randomGenerator.nextInt(50);
}
private static void FirstTimeInGame() {
String[] items = {"Warrior", "Mage", "Druid", "Scout"};
JComboBox combo = new JComboBox(items);
JTextField Name = new JTextField();
JPanel panel = new JPanel(new GridLayout(0, 1));
GenerateStatus();
panel.add(new JLabel("Name", SwingConstants.CENTER));
panel.add(Name);
panel.add(new JLabel("Class", SwingConstants.CENTER));
panel.add(combo);
panel.add(new JLabel("Stats", SwingConstants.CENTER));
panel.add(new JLabel("Strength " + STR));
panel.add(new JLabel("Attack Power " + aPower));
panel.add(new JLabel("Spell Power " + sPower));
panel.add(new JLabel("Intellect " + INT));
panel.add(new JLabel("Stamina " + STA));
panel.add(new JLabel("Armor " + DEF));
String[] buttons = {"Create!", "Randomize!", "Cancel"};
int result = JOptionPane.showOptionDialog(null,
panel,
"Welcome",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
buttons,
buttons[2]
);
if (result == JOptionPane.OK_OPTION) {
System.out.println(combo.getSelectedItem()
+ " " + Name.getText());
}
else if (result == JOptionPane.NO_OPTION){
GenerateStatus();
panel.validate();
panel.repaint();
}
else{
System.out.println("CANCEL");
}
}
public static void main(String[] args) {
FirstTimeInGame();
}
}
函数GenerateStatus()生成随机数。当我按下按钮'随机化!'窗户正在关闭
任何人都可以帮助我吗?请?
答案 0 :(得分:1)
您不需要将JLabel添加到面板,而是需要将它们存储在类级别成员中。 单击按钮时,需要更改现有标签中的文本。
在此附近:
public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0;
添加
private JLabel strLabel;
然后panel.add(new JLabel("Strength " + STR));
变为
strLabel = new JLabel("Strength " + STR);
panel.add(strLabel);
现在,您可以从其他地方更改strLabel
的文字。