编程语言
首页 > 编程语言> > Java Swing GridBagLayout组件定位

Java Swing GridBagLayout组件定位

作者:互联网

我第一次使用Swing的GridBagLayout,到目前为止我只在容器中添加了两个组件,尽管我打算在垂直方向下添加更多组件.到目前为止,第一个组件(一个JLabel)正确定位在PAGE_START,我记得为组件的相应GridBagConstraints设置权重属性.然而,第二个组件(一个JTextField)没有按照我的意图定位,它在容器中居中而不是在JLabel下面向上移动.我试图使用多个锚定常量,包括FIRST_LINE_START,PAGE_START,NORTH&西北,但到目前为止没有任何工作.

因此,我再次呼吁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);

图片如下;

谢谢大家提供的任何帮助.

解决方法:

尝试将addressLine1的权重增加到更大的值.我做了一个快速测试,将其设置为1000:

addressLine1GC.weighty = 1000.0;

并将addressLine1字段向上推到标签下面,下面是空格.

标签:gridbaglayout,java,swing,position
来源: https://codeday.me/bug/20190725/1533383.html