![](/img/trans.png)
[英]How to clear JFrame area by clicking another sub menu of JMenuBar in java Swing?
[英]Java Swing how to clear a JFrame?
不幸的是,我無法在任何地方找到我的問題的答案。
這是我的程序:
import javax.swing.*;
import java.awt.*;
public class TestClass {
public static void main(String[] args) {
JFrame window = new JFrame("Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,1));
JButton button = new JButton("Button");
button.addActionListener(e -> windowPreparation(window));
panel.add(button);
window.add(panel);
window.setSize(800, 600);
window.setVisible(true);
}
private static void windowPreparation(JFrame window) {
window.removeAll();
window.validate();
window.repaint();
}
}
我想要實現的目標:一旦按下按鈕,JFrame 應該被重置(我想用那個按鈕刪除那個 JPanel),這樣我就可以將它傳遞給另一個 class,然后用這個 Z97A6D72B9C04A8CACF22 做其他事情。 為了讓這個 class 可以毫無問題地做到這一點,我想事先清除 JFrame。 我剛剛嘗試過,因為它是寫在我的代碼中的,問題是它不起作用,只要我按下按鈕 window 就會凍結。 有誰知道我做錯了什么?
做window.remove(panel);
而不是window.removeAll()
:
IE:
import javax.swing.*;
import java.awt.*;
public class TestClass {
public static void main(String[] args) {
JFrame window = new JFrame("Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,1));
JButton button = new JButton("Button");
button.addActionListener(e -> windowPreparation(window, panel));
panel.add(button);
window.add(panel);
window.setSize(800, 600);
window.setVisible(true);
}
private static void windowPreparation(JFrame window, JPanel panel) {
window.remove(panel);
window.validate();
window.repaint();
}
}
我願意糾正為什么您的原始解決方案不起作用,但我認為這是因為JFrame
中的“基礎設施” Component
與您添加的組件無關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.