【问题标题】:Is it possible to reorder components in containers in some layouts?是否可以在某些布局中重新排序容器中的组件?
【发布时间】:2014-06-04 16:17:13
【问题描述】:

有一些布局,比如FlowLayout,按照添加的顺序来维护组件的顺序。

添加后是否可以排列某些组件?还是唯一的方法是清除所有组件并以新顺序重新添加它们?

【问题讨论】:

  • 您需要什么样的布局管理器?实际上,这取决于您选择的布局。例如。 GridbagLayout 使用约束,顺序无所谓
  • 不要替换组件; 更新组件的内容,用于example

标签: java swing layout-manager


【解决方案1】:

您可以使用JPanel#add(component,index)JPanel#remove(index) 轻松实现它

无需从容器中移除所有组件。只需移除所需组件并在所需位置添加新组件即可。

示例代码:

final JPanel panel = new JPanel(new FlowLayout());
for (int i = 0; i < 10; i++) {
    panel.add(new JButton(String.valueOf(i)));
}

JButton remove = new JButton("Remove");
remove.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        panel.remove(2);
        panel.revalidate();
    }
});

JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        panel.add(new JButton("21"), 2);
        panel.revalidate();
    }
});

【讨论】:

  • 你也可以考虑Continer#setComponentZOrder
  • 谢谢,我会进一步了解它。但它会在按顺序添加组件的 FlowLayout 中工作吗?
  • 并通过使用 repaint() 让所有通知器都完成,从未见过完整的解释,和/但我也无法回答原因
  • @Braj 基于(大多数)布局管理器在 z 顺序偏好中布局组件的事实,应该这样做;)
猜你喜欢
  • 2023-03-21
  • 2019-04-08
  • 2021-08-25
  • 1970-01-01
  • 2017-02-25
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多