如何等待文本字段中的输入? [英] How to wait for input in a text field?
问题描述
我正在将控制台应用程序转换为使用 Swing 的应用程序.目前我希望我的程序对这个 .nextInt();
做类似的事情,我怎样才能通过使用 .getText();
或类似的东西来实现这一点?
I'm converting a console application to one that uses Swing. At the moment I want my program to do a similar thing to this .nextInt();
how can I achieve this by using .getText();
or something similar?
简而言之;
如何在用户在文本字段中输入内容并按下 Enter 之前保持程序的执行.
How can I hold the execution of the program till the user has entered something in the text field and pressed enter.
推荐答案
更新: 所以你想等待用户从 GUI 输入一些东西.这是可能的,但需要同步,因为 GUI 在另一个线程中运行.
Update: So you want to wait for the user to to input something from the GUI. This is possible but needs to be synchronized since the GUI runs in another thread.
所以步骤是:
- 创建一个持有者"对象,将结果从 GUI 委托给逻辑"线程
- 逻辑"线程等待输入(使用
holder.wait()
) - 当用户输入文本时,它会同步holder"对象并给出结果+通知逻辑"线程(使用
holder.notify()
) - 逻辑"线程从其锁定中释放并继续运行.
<小时>
完整示例:
Full example:
public static void main(String... args) throws Exception {
final List<Integer> holder = new LinkedList<Integer>();
final JFrame frame = new JFrame("Test");
final JTextField field = new JTextField("Enter some int + press enter");
frame.add(field);
field.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
synchronized (holder) {
holder.add(Integer.parseInt(field.getText()));
holder.notify();
}
frame.dispose();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// "logic" thread
synchronized (holder) {
// wait for input from field
while (holder.isEmpty())
holder.wait();
int nextInt = holder.remove(0);
System.out.println(nextInt);
//....
}
}
这篇关于如何等待文本字段中的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!