我第一次使用Swing
's GridBagLayout
,到目前为止,我只在容器中添加了两个组件,尽管我打算在垂直下方添加更多组件。到目前为止,第一个组件 (a JLabel
) 正确定位在PAGE_START
,我记得为组件对应的GridBagConstraints
. 然而,第二个组件 (a 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);
下图;
感谢大家提供的任何帮助。