最近在这里问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();
}
});
}
};
最佳答案
在可见的 GUI 上添加或删除组件都是一样的:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
关于java - 如何从 JFrame 中删除 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501861/