Reputation: 33
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.
Upvotes: 0
Views: 4575
Reputation: 773
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 asmodal
, 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);
}
});
}
Upvotes: 1