简体   繁体   English

Java JPanel未绘制

[英]Java JPanel not painting

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. 我遇到了一个相当奇怪的问题-单击按钮后,程序将初始化一个新的JPanel对象,并尝试立即对其进行绘制。 After repaint(), it will open up a socket to a server and perform some interactions. repaint()之后,它将打开服务器的套接字并执行一些交互。 The issue I have is that repaint() doesn't paint the screen until after the socket interactions are done. 我的问题是,直到套接字交互完成后,repaint()才会绘制屏幕。 Here's the code. 这是代码。

creating the GameGUI JPanel object 创建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

constructing GameGUI JPanel object 构造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

The run() function paints a background for the GameGUI . run()函数为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. 如果我要在交互过程中杀死套接字与之交互的服务器,则会在GameGUI构造过程中发生异常以及绘画。

Consider posting an SSCCE , without it, it is hard to say what is the problem. 考虑发布SSCCE ,没有它,很难说出问题所在。 However, according to your description, you are may be blocking Event Dispatch Thread (EDT) with sockets interaction. 但是,根据您的描述,您可能正在通过套接字交互来阻止事件调度线程 (EDT)。

repaint() only schedules component update, it does not trigger immediate paint() . repaint()仅安排组件更新,它不会立即触发paint() Painting happens on EDT, so if you're blocking EDT then you're interfering with painting mechanism. 绘画是在EDT上进行的,因此,如果您阻止EDT,则可能会干扰绘画机制。

Consider using a worker thread to handle long running tasks. 考虑使用辅助线程来处理长时间运行的任务。 Check out SwingWorker , it is designed for this purpose. SwingWorker ,它就是为此目的而设计的。 Also look at Concurrency in Swing for more details on EDT. 另请参阅Swing中的并发,以获取有关EDT的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM