像Scanner一样检索JTextField内容

时间:2013-07-14 16:30:28

标签: java swing user-interface jtextfield

我正在尝试为我的程序设置一个GUI,并且已经完成了它的工作。但是,我希望能够创建一个像Scanner的nextLine()那样有效的方法;它等待来自我的JTextField的输入,然后返回它。似乎this question与我的非常相似,但没有等待用户的输入。这是我的GUI的当前代码:

package util;

import java.awt.Font;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import com.jgoodies.forms.factories.DefaultComponentFactory;

public class Gui {

    public JFrame frame;
    private JTextField textField;
    private final JLabel lblVector = DefaultComponentFactory.getInstance().createTitle("Please type commands below.");
    private JScrollPane scrollPane;
    private JTextArea textArea;

    /**
     * Create the application.
     */
    public Gui() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public void print(String text){
        textArea.append(text+"\n");
    }
    public String getInput()
    {
        String input = textField.getText();
        textField.setCaretPosition(0);
        return input;
    }
    private void initialize() {
        frame = new JFrame("Vector");
        frame.setBounds(100, 100, 720, 720);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        textField = new JTextField();
        frame.getContentPane().add(textField, BorderLayout.SOUTH);
        textField.setColumns(10);
        frame.getContentPane().add(lblVector, BorderLayout.NORTH);

        scrollPane = new JScrollPane();
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        textArea = new JTextArea();
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 15));
        textArea.setEditable(false);
        scrollPane.setViewportView(textArea);
    }
}

我希望能够这样称呼它:

String menus = gui.getInput();

等;我已经将gui变量设置为新的Gui()。

从我的搜索中,我收集它可能涉及DocumentListener或ActionListener,或两者兼而有之。

2 个答案:

答案 0 :(得分:4)

在文本字段中添加ActionListener。当文本字段具有焦点并且用户按 Enter 时,将触发事件。有关详细信息,请参阅How to Write an Action Listener

答案 1 :(得分:-1)

经过一番搜索,我发现this question回答了我的问题:

public String getInput() throws InterruptedException
{
    final CountDownLatch latch = new CountDownLatch(1);
    KeyEventDispatcher dispatcher = new KeyEventDispatcher() {
        // Anonymous class invoked from EDT
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER)
                latch.countDown();
            return false;
        }
    };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
    latch.await();  // current thread waits here until countDown() is called
    KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
    String input = textField.getText();
    textField.setCaretPosition(0);
    return input;
}

感谢大家的帮助!