【发布时间】:2017-06-14 23:08:34
【问题描述】:
在调用setHorizontalGroup() 和setVerticalGroup() 之后,是否可以在不重置布局的情况下将Components 动态添加到GroupLayout 中的组?我正在开发一个项目的 GUI,该项目将帮助学生找到整理每周课程表的最佳方式。这涉及为未知数量的课程输入关于上课时间等的信息。当然,我不能随便添加任意数量的表单让用户输入信息并说“没有人可以考虑超过这个数量的类”,所以用户需要能够添加新表单他们自己的。我可以创建表单,但是如果不重新调用setHorizontalGroup(...) 或setVerticalGroup(...),我找不到任何方法将它们成功添加到窗口中的GroupLayout,它们会覆盖以前的Groups 而不是添加给他们。
这是我目前拥有的代码的相关部分(为易读性而注释):
private static void createAndShowGUI() {
//Create window and assign an empty GroupLayout to it
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GroupLayout layout = new GroupLayout(frame.getContentPane());
frame.getContentPane().setLayout(layout);
/*WeekPanel extends JPanel, and is the "form" the user enters data into.
In essence, it's a JPanel with a series of JTextFields.*/
WeekPanel panel1 = new WeekPanel();
WeekPanel panel2 = new WeekPanel();
//The layout code below places two WeekPanels in the window, one on top of the other
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(panel1)
.addComponent(panel2)));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(panel1)
.addComponent(panel2));
/*I would like to add a component to the layout here as proof of concept.*/
frame.pack();
frame.setVisible(true);
}
我试过在frame.pack() 之前调用frame.add([some component]),但它从来没有产生任何明显的区别。我查看了 GroupLayout 的官方文档,我看不到在GroupLayout 中访问或更改水平/垂直Groups 的方法,甚至是引用那些Groups 的字段。
我完全不知道在这里做什么。如果可能的话,我想避免学习一种新的Layout,但我开始担心我将不得不这样做(或者,更糟糕的是,我正在尝试做的事情是不可能开始的与)。
【问题讨论】:
-
“这涉及为未知数量的课程输入有关上课时间等信息。” 听起来像是
JTable的工作。 “如果可能的话,我想避免学习一种新的Layout” 有必要了解一些布局,以及如何组合它们,然后才能使用您可能会成功完成任何基于 GUI 的非平凡应用程序。 (即使大部分信息都显示在JTable中。)
标签: java swing layout-manager grouplayout