[英]Thread in swing doesn't always run
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();
}
}
}
}
I have a code that looks like this. 我有一个看起来像这样的代码。 When I press the run button in Eclipse, sometimes it works properly, but sometimes the there would be nothing in the window at all, nothing painted and keys doesn't work.
当我在Eclipse中按下运行按钮时,有时它可以正常工作,但是有时窗口中根本没有任何东西,没有东西被涂上并且键不起作用。
I heard that using threads in GUI might cause concurrency problems, and I wonder if this is the case, and what I should do to correct it. 我听说在GUI中使用线程可能会导致并发问题,我想知道是否是这种情况,我应该怎么做才能解决。 Thanks.
谢谢。
stackoverflow.com/questions/369823/java-gui-repaint-problem stackoverflow.com/questions/369823/java-gui-repaint-problem
I found that this is exactly my case, and the solutions worked. 我发现这正是我的情况,解决方案也奏效了。
Though it appears my understanding to Swing is yet too shallow, I must go over the tutorial. 尽管我对Swing的理解似乎还不太浅,但是我必须仔细阅读本教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.