简体   繁体   English

Java:从JTextField获取用户输入

[英]Java: Get User Input from JTextField

Currently I'm using the following code to display a text field to user and retrieve the input from user. 目前,我正在使用以下代码向用户显示文本字段,并从用户检索输入。

public void getInputFromUser ()
{

    String input = null;
    JTextField textField = new JTextField();
    textField.setColumns(50);

    textField.setVisible(true);


    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    frame.setSize(300, 75);
    frame.add(textField);
    frame.setVisible(true);
    frame.requestFocus();
    frame.addWindowListener(null);


    textField.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent ae){

              String text = textField.getText();

              System.out.println(text);
           }
        });

This works fine. 这很好。 However the issue is: 但是问题是:

• I want to be able to get the input when user closes the dialog as appose to when user hits enter •我希望能够在用户关闭对话框时获取输入,以适合用户点击回车时的输入

• I want to stop the execution of the program until the user enters something and closes the dialog. •我想停止执行程序,直到用户输入内容并关闭对话框。 Right now the program continues to run even before user enters anything in dialog / text box. 现在,该程序甚至在用户在对话框/文本框中输入任何内容之前仍继续运行。

I know a one simple way, how you can do it. 我知道一个简单的方法,您怎么做。 When I need make something like it, I use JDialog always. 当我需要做类似的事情时,我总是使用JDialog。 If you set JDialog as modal , It stop execution of the program, if the JDialog is visible. 如果将JDialog设置为modal ,如果JDialog可见,它将停止程序的执行。 I updated your code below: 我在下面更新了您的代码:

 public void getInputFromUser ()
 {
    String input = null;
    JTextField textField = new JTextField("sadsadasd");
    textField.setColumns(50);

    textField.setVisible(true);

    JDialog jd = new JDialog();
    jd.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    jd.setSize(300, 75);
    jd.add(textField);
    jd.requestFocus();
    jd.setModal(true);
    jd.setVisible(true);
    System.out.println("I am here");

    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {

            String text = textField.getText();

            System.out.println(text);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM