gpt4 book ai didi

Java Swing - 如何暂停方法并等待按键?

转载 作者:行者123 更新时间:2023-12-01 21:57:12 30 4
gpt4 key购买 nike

我有一个 GUI,它有一个输出文本框和一个输入文本框。如果可以的话,我希望仅使用一个输入框来处理所有用户输入。我遇到一种情况,我问用户一个问题,他们输入答案,然后在方法内,我想使用相同的输入文本框提出一个子问题。但是,在我创建的处理此交互的方法中,到目前为止我无法更改文本框或按任何键。我应该如何修复我的代码?

编辑:考虑到评论指出我不应该使用 Thread.sleep(),我尝试使用计时器。但是,现在该方法不再等待,而是立即失败并返回“N”。请原谅我对 GUI 和 Swing Timer 还比较陌生。我需要做什么才能让程序等待,同时仍允许我键入并按 Enter 键?

    public static String pauseUntilKey(JTextField tf)
{
pause = true;

tf.removeKeyListener(tf.getKeyListeners()[0]);
KeyAdapter pauseForInput = new KeyAdapter() { //Get rid of the old keyAdapter and put in the new one just for this function
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER) //When the enter key is pressed, this should trigger
{
pause = false; //Set local variable pause to be false to let us know we need to stop the while loop
answer = tf.getText();
tf.setText("");
}
}
};
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(pause == false)
timer.stop();
}
});
timer.start();


KeyAdapter enterMain = new KeyAdapter() { //Put the old key adapter back in
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER)
{
roster = textInput(tf.getText(), roster, names, true, tf); //Analyze the line using textInput function, update the roster with any changes
tf.setText("");
}
}
};
tf.addKeyListener(enterMain);
if(pause == false)
return answer; //If we left the while loop the way I wanted, then return whatever the user wrote before pressing enter.
return "N"; //Otherwise, just return N for No.
}

最佳答案

变量pause需要声明为 volatile 的,否则工作线程永远不会收到事件调度线程中所做的更改的通知(这将调用keyPressed方法)。

另外,如果您还没有这样做,您需要使用一个 SwingWorker 实例来调用 pauseUntilKey,否则您会锁定整个 swing 子系统,因为它是单线程的。

关于Java Swing - 如何暂停方法并等待按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58734995/

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