Hi,
Please help me out with the following
Situation:
A login screen with only a “connect” button. Clicking the button should make the game connect to a server.
The server is not running, so it should just keep trying to connect (even though it never will) while not blocking the GUI.
Problem:
GUI freezes when I click the button. I have to kill the process with traskmanager.
Code:
This is the Thread that starts when the button is clicked:
private static class ButtonCallback implements Runnable {
Game game;
public ButtonCallback(Game game) {
this.game = game;
}
public void run() {
game.network.connect("XXX.XXX.XXX.XXX", XXXX); // edited out IP for privacy
}
}
This is the class containing the ‘connect()’ method:
public class Network {
Game game;
SocketChannel socketChan;
public Network(Game game) {
this.game = game;
socketChan = null;
}
public void connect(String server, int port) {
game.loginGui.lblStatus.setText("Connecting to: " + server + ":" + Integer.toString(port));
try {
socketChan = SocketChannel.open();
socketChan.configureBlocking(false);
socketChan.connect(new InetSocketAddress(server, port));
while (socketChan.isConnectionPending()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
game.loginGui.lblStatus.setText("Connected.");
} catch (UnknownHostException e) {
game.loginGui.lblStatus.setText("ERROR: Unknown host");
e.printStackTrace();
} catch (IOException e) {
game.loginGui.lblStatus.setText("ERROR: Failed to connect!");
e.printStackTrace();
}
}
}
I thought the Thread.sleep would make sure the GUI keeps working. Why doesn’t it?
Additional info:
Using LWJGL and TWL
Java eclipse
Windows 7