【发布时间】:2018-01-14 23:51:15
【问题描述】:
public class Interface extends JFrame
{
public Interface() throws InterruptedException
{
//windowsetup
pan = new MainPanel();
Thread t = new Thread(pan);
t.start();
add(pan);
addKeyListener(pan);
}
public static void main(String[] Args) throws InterruptedException
{
Interface proj = new Interface();
}
}
////////
public class MainPanel extends JPanel implements KeyListener, Runnable
{
public void paint(Graphics g)
{
//painting
}
public void run()
{
while(true)
{
this.repaint();
//other codes
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
我有一个看起来像这样的代码。当我在 Eclipse 中按下运行按钮时,有时它可以正常工作,但有时窗口中根本什么都没有,没有任何绘制,按键也不起作用。
我听说在 GUI 中使用线程可能会导致并发问题,我想知道是否是这种情况,以及我应该做些什么来纠正它。谢谢。
【问题讨论】:
-
你需要通过
SwingUtilities.invokeLater方法在EDT上运行repaint();方法。 -
是的,确实如此,并且 revalidate() 成功了,非常感谢!
-
nothing in the window at all,- 你永远不会让框架可见。使用 Swing Timer 制作动画。不要使用 KeyListener。而是使用`键绑定。不要覆盖paint()。自定义绘画通过覆盖paintComponent() 完成。这么多问题。首先阅读Swing Tutorial。我提出的所有上述建议都有部分内容。
标签: java multithreading swing