0

I try to write a Tic Tac Toe game between 2 devices with graphics and everything, but I have a problem. After I press a button I change its icon and then send the data via a socket and use blocking command to get the response. My problem is that I can see the change in the button's icon only after I get the response from the socket. Does anyone know what to do?

I learned sockets in python, and only recently I decided to try writing a program with sockets in java, so I don't have much experience in Java. I tried to delay the program before I wait for response, and to get 2 responses(one is automatic), but they both failed. I also tried to use timer to update the button's icons every tick, also didn't work.

That's the relevant part from my code

Socket sock;
PrintWriter pr;
InputStreamReader in;
BufferedReader bf;
public void click(int x, int y)
{
    buttons[x][y].setIcon(new ImageIcon("C:\\Users\\shaked\\Desktop\\red_Pin.jpg"));
    String msg = (char)x + "," + (char)y;
    try     {
    System.out.println("SLEEPING");
    Thread.sleep(1000);
    }
    catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    }
    pr.println(msg);
    pr.flush();
    String enemy_move = bf.readLine();
}
Laf
  • 7,965
  • 4
  • 37
  • 52
  • You should read about managing changes in the UI in Java. The EDT (Event Dispatcher Thread) is an important notion to be aware of. This [question](https://stackoverflow.com/questions/7229284/), and [this one](https://stackoverflow.com/questions/7217013/) too, could help you. – Laf Apr 16 '19 at 17:47

1 Answers1

0

You need to run the communication from a different thread. just create a new one like this.

 new Thread() {
      @Override
      public void run() {
        // code in here
      }
    }.start();