java - Java Swing - 如何暂停方法并等待按键?
问题描述
我有一个具有一个输出文本框和一个输入文本框的 GUI。如果可以合理地实现,我希望仅将一个输入框用于所有用户输入。我有一种情况,我问用户一个问题,他们输入他们的答案,然后在方法内部,我想使用同一个输入文本框问一个子问题。但是,在我为处理此交互而创建的方法中,到目前为止,我无法更改文本框或按任何键。我应该如何修复我的代码?
编辑:考虑到我不应该使用 Thread.sleep() 的评论,我尝试使用 Timer。但是,现在该方法不再等待,而是立即失败并返回“N”。请原谅我对 GUI 和 Swing Timers 比较陌生。我需要做什么才能让程序等待,同时仍然允许我键入并按 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,否则将永远不会通过 Event Dispatcher Thread(将调用该keyPressed
方法)中所做的更改通知工作线程。
此外,如果您还没有这样做,您需要使用SwingWorker
将调用的实例pauseUntilKey
,否则您将锁定整个 swing 子系统,因为它是单线程的。
推荐阅读
- java - Eclipse 和 Struts 2 缺少“s:text”的结束标记
- linux - 为什么触摸 - 不返回任何错误但没有创建文件 - ?
- flutter - 使用 BottomNavigationBar 时如何通过屏幕导航缓存 FutureBuilder 异步结果?
- javascript - 强制用户仅使用地点自动完成结果
- r - 读取 csv 文件无法打开连接
- excel - 尽管操作成功,但对象需要错误
- javascript - 多 div 的动画 scrollTop 问题
- spyder - 在 Spyder for MacOs 中设置为工作目录
- angular - 角度注入组件到另一个布局组件
- c# - “尝试激活“Application.Startup”时,无法解析“Microsoft.Extensions.Logging.ILogger`1[Application.Startup]”类型的服务。”