As many of you may know, when you have a while loop (or any loop for that matter) when an input method is called, the program stops and waits for input.
e.g.
while {
String input = in.readLine();
int x = 55; //This will not execute until input has been given a value
System.out.println (x + x);
}
Now I am using buttons for input. Is there any way I can do the same thing (halt the program in a loop) with the use of JButton, JPanel, JFrame etc. ?
NOTE: I am also open to use the Runnable () interface if required.
UPDATE:
I am using listeners for the button. This is the exact problem.
public void actionPerformed (ActionEvent x){ string = x.getActionCommand}
public void someOtherMethod ()
{
while (true){
start ();
if (string.equals ("exit") break; // This line will never execute because start()
//is always repeating itself.
}
}
EDIT:
I found a solution (FINALLY!)
this is all that needs to be done….
string = "";
while (true){
if (string.equals ("");
start ();
if (string.equals ("exit") break; // I guess I didn't explain the problem too well...
}
Thank you for everybody’s help!
I think the problem you’re having is how to change what the button does depending on what has been entered into the GUI. Remember that with a GUI, the user can interact with any enabled GUI component at any time and in any order. The key is to check the state of the GUI in your button’s ActionListener and then altering the behavior of this method depending on this GUI’s state. For example if your GUI had three JTextFields, field1, field2, and sumField and a JButton addButton:
And you wanted the addButton to add the numbers in field1 and field2 together and place the results into the sumField, you’re obviously not going to want to do any addition if either field is left blank, and so you test for it in the JButton’s ActionListener:
Here’s the whole thing:
EDIT 1
Otherwise if you absolutely have to use a loop, then yes, do it in a Runnable and do that in a background Thread. Remember to call Thread.sleep(…) inside of the loop even for a short bit so it doesn’t hog the CPU. For example