Rom*_*man 2 java user-interface swing visibility jpanel
我想从Window(JFrame)中删除一个旧的JPanel并添加一个新的。我该怎么办?
我尝试了以下方法:
public static void showGUI() {
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(partnerSelectionPanel);
frame.setSize(600,400);
frame.setVisible(true);
}
private static void updateGUI(final int i, final JLabel label, final JPanel partnerSelectionPanel) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
label.setText(i + " seconds left.");
}
partnerSelectionPanel.setVisible(false); \\ <------------
}
);
}
Run Code Online (Sandbox Code Playgroud)
我的代码更新了“旧” JPanel,然后使整个JPanel不可见,但它不起作用。编译器抱怨用指示的行<------------。它写道:<identifier> expected, illegal start of type。
添加:
我已经设法完成了我需要做的事情,并且通过以下方式做到了:
public static void showGUI() {
frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(partnerSelectionPanel);
//frame.add(selectionFinishedPanel);
frame.setSize(600,400);
frame.setVisible(true);
}
public static Thread counter = new Thread() {
public void run() {
for (int i=4; i>0; i=i-1) {
updateGUI(i,label);
try {Thread.sleep(1000);} catch(InterruptedException e) {};
}
partnerSelectionPanel.setVisible(false);
frame.add(selectionFinishedPanel);
}
};
Run Code Online (Sandbox Code Playgroud)
它可以工作,但由于以下原因,在我看来它不是一个安全的解决方案:
我应该这样做吗?
setVisible(false),即使在正确的位置,也实际上不会从容器中移除面板。如果要更换面板,请执行以下操作:
frame.getContentPane().remove(partnerSelectionPanel);
frame.add(new JPanel());
frame.getContentPane().invalidate();
frame.getContentPane().validate();
Run Code Online (Sandbox Code Playgroud)
请注意,frame.getContentPane()。add(Component)与frame.add(Component)相同-组件实际上包含在内容窗格中。