我正在写一个基于文本的冒险游戏,我遇到了一个问题。 我正在将它从终端移植到JFrame GUI,我需要它在继续之前等待用户输入。 我建立了一个系统,其中有一个名为buttonPressed的布尔变量,它以false开头。 按下提交文本按钮后,将其更改为true。 有一个while循环在允许程序继续之前等待按钮变为true,基本上暂停程序直到用户提交输入。 问题是这只有当我在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!
");
}
你定义了buttonPressed吗?
是的,在顶部我用private static boolean buttonPressed = false初始化它; 这很奇怪,因为当我有一行代码时,它可以工作
然后我猜想JVM会跳过空的无限循环。 也许你可以使用Thread.sleep(15)?
缺少buttonPressed定义......看起来你有两个? 用不完整的代码很难说。
你能提供更多代码吗? 如何将ActionListener附加到按钮?
我首先看看Java中的Concurrency。 我还要看看如何制作能够解决基本问题的对话框
我没有java专家,但......
看起来你没有给你的gui线程时间做任何事情,因为你正忙着等待你的布尔值改变。
要解决这个问题,你应该使用信号量。或者,更容易(脏)的解决方案,在while循环中调用sleep()。
对于java特定的东西,请看这个问题。
第二个想法,我发现java有一个volatile关键字。我不知道buttonPressed是否被声明为volatile,但如果不是,编译器可能会决定,因为while循环是空的,它的值永远不会改变,并用while(true)替换它作为优化。
这个...
while(!buttonPressed){
// this only works when I have system.out.println("something") written in
}
只是要求麻烦,除了你不能保证实际调用了什么线程main,这可能导致你阻塞事件调度线程,这只是错误的方法。
您不想使用JFrame,而是使用某种模式JDialog,这将阻止代码在对话框可见时执行,直到它被处理/关闭,并以安全的方式执行,因此您可以在EDT的背景下使用它。
有关更多详细信息,请查看初始线程,Swing中的并发以及如何创建对话框。
作为一般建议,避免直接从顶级容器(如JFrame和JDialog)扩展,而是选择使用JPanel之类的东西,它可以让您解放并增加组件的可重用性