【发布时间】:2016-04-06 20:20:24
【问题描述】:
我正在编写基于文本的冒险游戏,但遇到了问题。我将它从终端移植到 JFrame GUI,我需要它在继续之前等待用户输入。我建立了一个系统,其中有一个名为 buttonPressed 的布尔变量,它一开始是假的。当按下提交文本按钮时,它会将其更改为 true。在允许程序继续之前,有一个 while 循环等待按钮变为真,实质上是暂停程序,直到用户提交输入。问题是这仅在我在 while 循环中写入 system.out.println 行时才有效。否则,单击按钮后它不会继续。有什么问题?
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
moves += 1;
movesLabel.setText("Moves: " + moves);
buttonPressed = true;
try{
input = (String)(textfield.getText());
textfield.setText("");
}catch(Exception ex){
textfield.setText("Error");
}
}
}
public static void main (String args[]) {
Main gui = new Main();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(650, 350);
gui.setTitle("Sprinkles Text Adventure");
setInventory();
textArea.setText(textDisplay("Welcome Adventurer!"));
textArea.setText(textDisplay("What is thy name: "));
while(!buttonPressed){
// this only works when I have system.out.println("something") written in
}
buttonPressed = false;
textArea.setText(textDisplay(input));
if ("alice".equals(input)||"Alice".equals(input)){
textArea.setText(textDisplay("Stop toking the magical pipe, "));
textArea.setText(textDisplay("you aren't alice and this isn't wonderland"));
textArea.setText(textDisplay("Now down the rabbit hole you go!"));
}
else if ("l3ikezI".equals(input)||"l3ikezi".equals(input)){
System.out.println("Magic and Technology flows through your veins");
System.out.println("Welcome back, Master");
for(int j = 0; j<14; j++){
Chest[j]=1;
}
}
else{
System.out.println("Enter " + input + " and good luck!\n\n");
}
【问题讨论】:
-
你定义
buttonPressed了吗? -
是的,最重要的是我用私有静态布尔按钮Pressed = false;这很奇怪,因为当我有那一行代码时它可以工作
-
那么我猜JVM会跳过空的无限循环。也许你可以使用 Thread.sleep(15) ?
-
buttonPressed定义丢失...看起来您有两个?代码不完整很难说。 -
您能提供更多代码吗?如何将 ActionListener 附加到按钮?
标签: java loops user-interface while-loop jframe