I'm converting a console application to one that uses Swing. At the moment I want my program to do a similar thing to this .nextInt();
how can I achieve this by using .getText();
or something similar?
In short;
How can I hold the execution of the program till the user has entered something in the text field and pressed enter.
Update: So you want to wait for the user to to input something from the GUI. This is possible but needs to be synchronized since the GUI runs in another thread.
So the steps are:
holder.wait()
)holder.notify()
)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);
//....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With