【发布时间】:2011-01-30 21:44:59
【问题描述】:
最近我在这里问how to add a new JPanel to JFrame。答案帮助我获得了工作代码。但我没有相关的问题:“如何删除旧的 JPanel”。由于以下问题,我需要它。
当我需要时会出现一个新的 JPanel(超过时间限制或用户按下“提交”按钮)。但在几秒钟内,旧 JPanel 的某些元素与新 JPanel 的组件一起出现。我不明白为什么会这样。
我认为这是因为我必须更新窗口的其他线程。但是第一个线程只添加一次旧面板(所以,它应该完成)。在第二个线程中,我有一个被破坏的循环(因此,它也应该完成)。
这是我的代码:
private Thread controller = new Thread() {
public void run() {
// First we set the initial pane (for the selection of partner).
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.getContentPane().add(generatePartnerSelectionPanel());
frame.invalidate();
frame.validate();
}
});
// Update the pane for the selection of the parnter.
for (int i=40; i>0; i=i-1) {
final int sec = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
timeLeftLabel.setText(sec + " seconds left.");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
if (partnerSubmitted) {
break;
}
}
// For the given user the selection phase is finished (either the time is over or form was submitted).
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.getContentPane().add(generateWaitForGamePanel());
frame.invalidate();
frame.validate();
}
});
}
};
【问题讨论】:
-
这似乎与您自己的问题重复:stackoverflow.com/questions/2487658/…
标签: java user-interface swing multithreading