2012-10-07 181 views
0

我有这个相当奇怪的问题 - 点击按钮后,程序将初始化一个新的JPanel对象并尝试立即绘制它。 repaint()后,它将打开一个服务器的套接字并执行一些交互。我遇到的问题是repaint()在套接字交互完成之前不会绘制屏幕。这是代码。Java JPanel没有绘画

创建GameGUI JPanel的对象

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 

构建GameGUI JPanel的对象

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 

run()函数描绘为GameGUI的背景。在套接字调用之后,它正确地绘制背景。如果我要杀死套接字在交互过程中与之交互的服务器,则会在GameGUI构建中发生异常并伴随着绘制。

+0

为了确保我已经正确理解了你,你想在网络上启动一个连接来初始化一个对象,然后将它添加到面板,然后重新绘制。如果是这样,你不能消费你还没有的东西。 – user1406062

+0

不,我只是在绘制一些可用的东西,执行一个不相关的网络动作,然后绘制其他东西。第一个油漆不通过。 – wonton

+0

这里有一个工作[示例](http://stackoverflow.com/a/3245805/230513)。 – trashgod

回答

4

考虑发布SSCCE,如果没有它,很难说出了什么问题。不过,根据您的描述,您可能会阻止事件调度线程(EDT)与套接字的交互。

repaint()只调度组件更新,它不会立即触发paint()。绘画发生在美国东部时间,所以如果你阻止美国东部时间,那么你正在干预绘画机制。

考虑使用工作线程来处理长时间运行的任务。检查出SwingWorker,它是专门为此目的而设计的。有关EDT的更多详情,请参阅Concurrency in Swing