How to wait for input in a text box?

I am converting a console application into an application using Swing. At the moment, I want my program to do this with this .nextInt(); how can I achieve this using .getText(); or something similar?

In short,

How can I execute the program until the user enters something in the text box and enters the input.

+6
source share
2 answers

Update:. Therefore, you want to wait for the user to enter something from the GUI. This is possible, but needs to be synchronized as the GUI starts in a different thread.

So the steps are:

  • Create a holder object that associates the result with a graphical interface with a logical flow
  • A "logical" thread is waiting for input (using holder.wait() )
  • When the user has entered the text, he synchronizes the holder object and gives the result + notifies the logical flow (using holder.notify() )
  • The "logical" thread is freed from blocking it and continues.

Full example:

 public static void main(String... args) throws Exception { final List<Integer> holder = new LinkedList<Integer>(); final JFrame frame = new JFrame("Test"); final JTextField field = new JTextField("Enter some int + press enter"); frame.add(field); field.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { synchronized (holder) { holder.add(Integer.parseInt(field.getText())); holder.notify(); } frame.dispose(); } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); // "logic" thread synchronized (holder) { // wait for input from field while (holder.isEmpty()) holder.wait(); int nextInt = holder.remove(0); System.out.println(nextInt); //.... } } 
+5
source

The console application and the GUI application are very different in their behavior. The console application accepts input from command line arguments or expects the user to enter keyboard input, while the GUI application is controlled by an event mechanism to complete the task.

For example, you add a TextField object to your frame and add keyListener to the text field object. The listener is called when a key event is notified. There are many examples, for example, the official java example http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html

0
source

Source: https://habr.com/ru/post/896121/


All Articles