如何等待输入文本字段? [英] How to wait for input in a text field?

查看:130
本文介绍了如何等待输入文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我转换一个控制台应用程序,以一个使用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?

在短;

我如何保持程序的执行,直到用户输入的东西在文本字段和pressed进入。

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.

因此​​,步骤是:


  1. 创建一个支架的对象,从GUI deligates结果为逻辑线程

  2. 对于输入的逻辑线程等待(使用 holder.wait()

  3. 当用户输入文本进行同步的持有人对象,并给出结果+通知逻辑线程(与 holder.notify()

  4. 的逻辑线程从它锁释放仍在继续。

完整的示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆