Okay, so I've seen a lot of questions like this here, but none of the provided answers seem to work for my particular case.
I have a game simulation program written in two parts; I wrote the actual functionality first, and then the GUI to display it all. I figured that when I was done I'd just implement calls back and forth to make the two talk to one another. The back-end used JOptionPane in the meantime to get user input.
My problem is that now that I want to display things in the GUI, I can't figure out how to pause the running of the program to wait for that to happen. For example, I had this in my original version:
private static void runAttackerTurn(Team off, Team def) {
int counter = 0;
while (counter < 4 && off.whoHasIt() != null) {
//Do some stuff
active = getActive(off, def, counter);
select = (String)JOptionPane.showInputDialog(null,
"Who Would " + active.getName() + " Like To Attack?" + "\n" +
off.whoHasIt().getName() + " has the ball",
"Turn " + turnCount + " - " + teamName + " Attacker Turn" ,
JOptionPane.INFORMATION_MESSAGE, null,
attackerOptions, attackerOptions[0]);
target = getTarget(off, def, select, counter);
attack((Forward)active, target);
//More stuff
counter++;
}
}
And it worked just fine. But when I have a GUI that I'd like to use instead of JOptionPane it all breaks down. The GUI has a JPanel
containing a JLabel
for the text, a JComboBox
for the list options, and a JButton
to confirm. What I would like to do is have the program "pause", effectively, and wait for the user to hit the button, then take the selected item, put that in select
and continue on.
I can't break the method up into two parts, as I originally tried, because I need to send other things besides just the result of select
into the second part.
Also, it might not be apparent from the above, but I do this about twenty or thirty times in different methods over the course of the program, so I really need a general solution rather than a quick fix.
I thought doing this with multiple threads might work, but I can't seem to get that right (the main thread stops executing too early - the button doesn't even show up to be clicked) and anyway, I'd prefer something simpler.
Also, in case this isn't perfectly clear, what I am really trying to do is simulate the modal property of JOptionPane within a JPanel that's embedded in the GUI, and make the method wait for the user input before continuing.
Any ideas?