正在检索类似于扫描仪的JTextField内容



我正试图为我的一个程序设置一个GUI,并且已经基本上可以工作了。然而,我希望能够创建一个非常像Scanner的nextLine()的方法;它等待我的JTextField的输入,然后返回。这个问题看起来和我的很相似,但没有等待用户的输入。这是我的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,或者两者兼而有之。

ActionListener添加到文本字段中。当文本字段具有焦点并且用户按下Enter时,将触发一个事件。有关更多详细信息,请参阅如何编写Action Listener。

经过一点搜索,我发现了这个问题,它回答了我的问题:

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;
}

感谢大家的帮助!

最新更新