我尝试在相同的X和Y步骤中将JLabel从位置a移动到位置B。该方法工作正确,但不更新我的gui..我在下面展示了我的代码:
当我不叫的时候。join()
方法,代码工作,但不要等待我的另一个线程的执行…我需要这个函数在实际运行时不调用。有人能帮帮我吗?
Thread MoveThread = new Thread( new Runnable()
{
@Override
public void run()
{
for (int i = 0; i<Const.SteinVerschiebenSchritte; i++)
{
try
{
p_lblToMove.setLocation(p_lblToMove.getLocation().x + x_schritt, p_lblToMove.getLocation().y + y_schritt);
System.out.println("SetLoc");
Thread.sleep(10);
}
catch (InterruptedException ex)
{
StatusLog("InterruptedException");
}
}
System.out.println("invokeLater");
p_lblToMove.setLocation(p_lblToMove.getLocation().x + x_offset, p_lblToMove.getLocation().y + y_offset);
}
});
MoveThread.start();
try {
System.out.println("BeforeJoin");
MoveThread.join();
System.out.println("AfterJoin");
System.out.println("------------------");
} catch (InterruptedException ex) {
Logger.getLogger(Spielfeld.class.getName()).log(Level.SEVERE, null, ex);
}
Swing是一个单线程环境,这意味着你不应该在事件调度线程的上下文中执行任何长时间运行或阻塞操作,同样,你的Swing也不是线程安全的,这意味着你应该只从事件调度线程的上下文中更新UI。
参见Swing中的并发。
根据你想要实现的目标,你可以使用SwingWorker
,参见Worker Threads和SwingWorker了解更多细节,或者使用Swing Timer
,参见如何使用Swing Timers了解更多细节
还请记住,Swing依赖于布局管理器来完成大部分核心工作,当涉及到组件的定位和大小调整时,您可能会发现您正在与布局管理器作斗争,这可能会导致意想不到的结果
当然,你可以看看通用渐变引擎和滑动布局或者Java:使用Timer