gpt4 book ai didi

java - 在 GridBagLayout 中正确删除元素

转载 作者:行者123 更新时间:2023-12-02 06:47:21 26 4
gpt4 key购买 nike

jPanel1 = new JPanel();
GridBagLayout layout = new GridBagLayout();
jPanel1.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();


filler = new JLabel();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;

jPanel1.add(filler, gbc);

我尝试通过执行 jPanel1.remove(filler) 来删除,然后在该位置放置一个新的 JLabel,但显然不起作用。我做错了什么?

谢谢!

最佳答案

如果filler只是一个JLabel,那么你可以这样做

filler.setText("add text here");

或者,如果您要替换不同的组件,更好的方法是创建一个使用卡片布局的面板。然后你可以交换这两个组件。请参阅 How to Use Card Layout 上的 Swing 教程了解更多信息。

另一种选择可能是执行以下操作:

GridBagLayout layout = (GridBagLayout)jPanel1.getLayout();
GridbagConstraint gbc = layout.getConstraint(oldComponent);
jPanel1.remove(oldComponent);
jPanel1.add(newComponent, gbc);
jPanel1.revalidate();
jPanel1.repaint();

关于java - 在 GridBagLayout 中正确删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18478933/

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