My title is somewhat cryptic but I couldn't come up with a clear one.
First, two code snippets to establish a point of reference (hopefully I have no typos):
Input with Scanner
'''
Scanner sc = new Scanner(System.in);
for (int i=0; i<10; ++ i) {
System.out.print("Please input a value:");
String answer = sc.next();
// do something with this string
}
...
Input with JOptionPane
:
...
for (int i=0; i<10; ++ i) {
String answer = JOptionPane.showInputDialog("Please input a value");
// do something with this string
{
So, in the above samples we're asking a user to enter a value a fixed number of times. How can I implement the same kind of functionality in a Swing application?
I have no problem creating a JFrame
with JPanel
(as its content pane) and adding JLabel
(with prompt) and JTextField
to this panel. I can also create ActionListener
for the text field which ActionPerformed
method to retrieve the value and process it. String processing is not a long-running task so I do not believe I will need a separate worker thread.
Since we can't really force user to do anything, I plan to use javax.swing.Timer
to ensure a timely response.
What I do not understand is how to implement the loop or any other form of control to ensure that a user enters (and the program retrieves) the value the exact number of times. How do I inject such logic into an event-driven system?
Once I set-up the GUI part and submit its instance to be invoked on EDT I seem to be relinquishing all control.
Do I initially submit my text field with setEditable
set to false
and then create a loop that will invokeAndWait
a Runnable
to enable the edit (and disable it back in the ActionPerformed
)?
Please point me into the right direction.
Well it depends on how you want to achieve it...
You could...
Provide the required number of fields (10 in your example) and a
JButton
, so that until all the fields are filled out, clicking the button will simply provide the user with a message and re-focus the invalid field...You could...
Provide the user with a single field (and label) and button. Until they fill out the field, pressing the button prompts them and re-focuses the field.
When the user fills out the required information and clicks the button, you increment a counter, reset the field and carry on until your counter reaches it's limit...
You could...
Use a
JTable
which has only one column and five rows...this is simplified (depending on your perspective) solution to the first solution...