简体   繁体   中英

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. If you set JDialog as modal , It stop execution of the program, if the JDialog is visible. 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);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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