gpt4 book ai didi

java - 从 JPanel 中动态删除组件

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:58 25 4
gpt4 key购买 nike

这是解释问题的可运行代码 -

我可以删除 s1 和 s2 但不能删除 s3。
这似乎与 MigLayout 无关(我碰巧正在使用它),因为我在默认布局中也看到了相同的行为。


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

public class MyFrame2 extends JFrame {
private JPanel main;
private JPanel s1;
private JPanel s2;
private JPanel s3;

public static void main(String[] args) throws InterruptedException {
MyFrame2 f = new MyFrame2();
f.setVisible(true);
Thread.sleep(2000); //you can see all three panels for two seconds

f.main.remove(f.s1);
f.main.validate();
Thread.sleep(2000);
f.main.remove(f.s2);
f.main.validate();
Thread.sleep(2000);
f.main.remove(f.s3);
f.main.validate();
}

public MyFrame2() {
main = new JPanel();

main.setLayout(new MigLayout());

main.add(new JLabel("Why does s3 not disappear?"),"w 200, h 100, wrap");

s1 = new JPanel();
s1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s1"));
main.add(s1,"w 90%, h 300, wrap");

s2 = new JPanel();
s2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s2"));
main.add(s2,"w 90%, h 300, wrap");

s3 = new JPanel();
s3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s3"));
main.add(s3,"w 90%, h 300, wrap");

getContentPane().setLayout(new BorderLayout());
getContentPane().add(main, BorderLayout.CENTER);

setSize(new Dimension(800, 600));

}
}

最佳答案

在最后一个 f.validate() 之后调用:

f.repaint(50L);

因为最后的验证不会改变布局。

关于java - 从 JPanel 中动态删除组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9169350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com