Java JOptionPane.showInputDialog() getting called more than once when code only says once
Okay, so I'm making a online fighting game and the dialog where you input the server IP keeps popping up again and again even though the code only asks for it once. It's not in any kind of loop though, so I dunno what's going on.
public void connectAndInit(){
try{
String ip = JOptionPane.showInputDialog("Input server IP.");
players = new Player[MAX_PLAYERS];
players[0] = new Player(25,25,135);
players[1] = new Player(750,550,315);
ct = new ClientThread(ip, players);
ct.start();
ct.setPriority(Thread.MAX_PRIORI开发者_StackOverflowTY);
playerNum = ct.playerNum;
init = false;
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void update()
{
if(init)
connectAndInit();
}
Here is the game with the problem: http://prime.programming-designs.com/java/metaship-client.jnlp
And here is the server you need to start before you run the game: http://prime.programming-designs.com/java/metaship-server.jnlp
I'd need to see the class hierarchy to be sure, since I'm not 100% on when and why update()
is called but here's what I suspect is happening.
update()
is being called twice, once initially (when you first show your JOptionPane
) and again for some reason. Possibly when the JOptionPane
is show, destroyed, or when it causes a repaint in some other component.
The gotcha is that while the JOptionPane is shown execution on that thread has stopped, so when it is closed there's a mad scramble for execution threads and connectAndInit()
is often (or always) called before init=false
is reached. If the calls to update()
are coming from different threads it's probably an always proposition.
To fix this, change your code to:
if(init){
init=false;
connectAndInit();
}
And dispense with the init=false;
in connectAndInit()
.
Let's say update()
gets called a hundred times at once in a hundred different threads. init
will be true in every thread, so connectAndInit()
will be called a hundred times, and thus your dialog box will be shown a hundred times.
I'm not sure if that's necessarily what's happening here, but it very well could be.
Good case for using your debugger.
Anyway, my guess would be to check that the init variable you're setting is not set elsewhere, e.g. by a separate thread.
精彩评论