【问题标题】:Java JPanel not paintingJava JPanel 不绘画
【发布时间】:2012-10-07 01:45:15
【问题描述】:

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

创建 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 构造时发生的绘制。

【问题讨论】:

  • 为了确保我对您的理解正确,您想在网络上启动连接以初始化对象,然后将其添加到面板,然后重新绘制。如果是这样,你就不能消费你还没有的东西。
  • 不,我只是在画一些可供我使用的东西,执行一个不相关的网络动作,然后再画一些别的东西。第一次油漆没有通过。
  • 这是一个有效的example

标签: java swing jpanel paint repaint


【解决方案1】:

考虑发布SSCCE,没有它,很难说是什么问题。但是,根据您的描述,您可能正在阻塞 Event Dispatch Thread (EDT) 与套接字交互。

repaint() 只安排组件更新,不会立即触发paint()。绘画发生在 EDT 上,所以如果你阻止 EDT,那么你就是在干扰绘画机制。

考虑使用工作线程来处理长时间运行的任务。查看SwingWorker,它就是为此目的而设计的。另请查看Concurrency in Swing,了解有关 EDT 的更多详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2021-10-23
    • 2017-08-31
    • 1970-01-01
    相关资源
    最近更新 更多