0

I'm having this rather strange issue - upon a button click, the program initializes a new JPanel object and attempts to paint it right away. After repaint(), it will open up a socket to a server and perform some interactions. The issue I have is that repaint() doesn't paint the screen until after the socket interactions are done. Here's the code.

creating the GameGUI JPanel object

this.startmenu.setVisible(false);
//startmenu is what the user looks at prior to clicking the button
this.game = new GameGUI(this, this.saver,
                        new Player(this.startmenu.getPlayerDataSelection()), in);
this.game.run();//performs the socket interactions

constructing GameGUI JPanel object

this.game = new PlayingFieldGUI();
//this is a panel inside the panel
this.setLayout(new FlowLayout());
//just need game panel and users panel side by side
this.add(this.game);
this.client.add(this);//client is the jpanel that holds this
this.setVisible(true);
this.game.setVisible(true);
this.client.repaint();//attempting to repaint

The run() function paints a background for the GameGUI. After doing the socket calls, it properly paints the background. If I were to kill the server that the socket interacts with in the middle of interactions, an exception throw occurs along with the painting that should have occurred at GameGUI construction.

tenorsax
  • 21,123
  • 9
  • 60
  • 107
wonton
  • 7,568
  • 9
  • 56
  • 93
  • Just to be sure I have understood you correctly, you want to initiate a connection on the network to initialize an object then add it to the panel and then repaint. If so, you can not consume something you that is not available yet. – user1406062 Oct 07 '12 at 02:00
  • No, I'm merely painting something available to me, performing an unrelated network action, then painting something else. The first paint does not go through. – wonton Oct 07 '12 at 02:58
  • Here's a working [example](http://stackoverflow.com/a/3245805/230513). – trashgod Oct 07 '12 at 03:03

1 Answers1

4

Consider posting an SSCCE, without it, it is hard to say what is the problem. However, according to your description, you are may be blocking Event Dispatch Thread (EDT) with sockets interaction.

repaint() only schedules component update, it does not trigger immediate paint(). Painting happens on EDT, so if you're blocking EDT then you're interfering with painting mechanism.

Consider using a worker thread to handle long running tasks. Check out SwingWorker, it is designed for this purpose. Also look at Concurrency in Swing for more details on EDT.

tenorsax
  • 21,123
  • 9
  • 60
  • 107