sách gpt4 ai đã đi

java - 如何删除旧的 JPanel 并添加新的 JPanel?

In lại 作者:行者123 更新时间:2023-12-03 02:55:25 29 4
mua khóa gpt4 Nike

我想从窗口 (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() {
công khai void run() {
label.setText(i + " seconds left.");
}
partnerSelectionPanel.setVisible(false); \\ <------------
}
);
}

我的代码更新了“旧”JPanel,然后它使整个 JPanel 不可见,但它不起作用。编译器提示 <------------ 指示的行。它写道: 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() {
công khai 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);
}
};

它确实有效,但在我看来,它并不是一个安全的解决方案,原因如下:

  1. 我从另一个线程更改元素并将其添加到 JFrame。
  2. 在“打包”JFrame 并使其可见后,我将新的 JPanel 添加到 JFrame 中。

我应该这样做吗?

1 Câu trả lời

setVisible(false),即使在正确的位置,也不会实际从容器中删除面板。如果您想更换面板,请执行以下操作:

frame.getContentPane().remove(partnerSelectionPanel);
frame.add(new JPanel());
frame.getContentPane().invalidate();
frame.getContentPane().validate();

请注意,frame.getContentPane().add(Component) 与frame.add(Component) 相同 - 组件实际上包含在内容 Pane 中。

关于java - 如何删除旧的 JPanel 并添加新的 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2487658/

29 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com