像Scanner一样检索JTextField内容 [英] Retrieving JTextField Contents Like Scanner

查看:128
本文介绍了像Scanner一样检索JTextField内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set up a GUI for a program of mine, and have got it mostly working. However, I would like to be able to create a method that works a lot like Scanner's nextLine(); it waits for the input from my JTextField, and then returns it. It seemed like this question was very similar to mine but did not wait for the user's input. Here is my GUI's current code:

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()。

or such; I've already set up the gui variable as a new Gui().

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

From my searches, I've gathered it would probably involve either a DocumentListener, or an ActionListener, or both.

推荐答案

添加 ActionListener 到文本字段。当文本字段具有焦点并且用户按 Enter 时,将触发事件。有关详细信息,请参阅如何编写动作侦听器

Add an ActionListener to the text field. When the text field has focus and the user presses Enter an event will be fired. See How to Write an Action Listener for more details.

这篇关于像Scanner一样检索JTextField内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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