我第一次使用 Swing 的 GridBagLayout,并且目前只向容器中添加了两个组件,尽管我打算在垂直方向上添加更多组件。到目前为止,第一个组件(一个 JLabel)在 PAGE_START 正确地定位,而且我已经记得为组件对应的 GridBagConstraints 设置权重属性。然而,第二个组件(一个 JTextField)没有按照我想要的方式定位,而是居中于容器,而不是在 JLabel 下面移动。我尝试使用多个锚定常量,包括 FIRST_LINE_START、PAGE_START、NORTH 和 NORTHWEST,但目前什么都没用。
因此,我再次呼吁 stackoverflow 的有才华的程序员们帮助解决问题。下面是代码片段,下面是问题的图形化图像。
// Instantiate components and configure their corresponding GridBagConstraints attributes
// refPlusType properties
refPlusType = new JLabel("<html><h3>"+"Reference"+" - "+"Job Type"+" </h3><hr /></html>");
refPlusTypeGC = new GridBagConstraints();
refPlusTypeGC.gridx = 0; // Grid position
refPlusTypeGC.gridy = 0;
refPlusTypeGC.gridwidth = 2; // Number of colums occupied by component
refPlusTypeGC.insets = new Insets(5, 10, 5, 10); // Specifies margin
refPlusTypeGC.weightx = 0.1; // Required for anchor to work.
refPlusTypeGC.weighty = 0.1; // Required for anchor to work.
refPlusTypeGC.anchor = GridBagConstraints.PAGE_START; // Position in container
// addressLine1 properties
addressLine1 = new JTextField();
addressLine1GC = new GridBagConstraints();
addressLine1GC.gridx = 0;
addressLine1GC.gridy = 1;
addressLine1GC.gridwidth = 2;
addressLine1GC.insets = new Insets(0, 10, 0, 10);
addressLine1GC.fill = GridBagConstraints.HORIZONTAL; // Specifies component fill Horizontal space
addressLine1GC.weightx = 0.1;
addressLine1GC.weighty = 0.1;
addressLine1GC.anchor = GridBagConstraints.FIRST_LINE_START;
// Add components to this HALLogisticsDetailsPanel
this.add(refPlusType, refPlusTypeGC);
this.add(addressLine1, addressLine1GC);
下面是图片;
非常感谢您提供的任何帮助。
weighty
的值会发生什么?只保留weightx
的值会怎样? - nIcE cOwaddressLine1GC.anchor = GridBagConstraints.NORTH;
- Guillaume Polet