我正在尝试使用GridBagLayout完成以下任务:

该框架将接收“字段”(JLabel,JTextField对)的集合,我想以“网格状”的方式排列它们,其中一行将包含2个这样的对(JLabel1 JField1 JLabel2 JField2)。当一行具有这四个组件时,下一个组件将添加到另一行。

编辑:我希望组件从面板顶部开始

我的代码产生以下布局。我希望组件布局更紧凑(尤其是垂直距离)

java - 使GridBagLayout更紧凑-LMLPHP


这是代码:

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class Test extends JFrame{

private JPanel _panel;

public Test() {
    this.setDefaultCloseOperation(HIDE_ON_CLOSE);
    this.setResizable(true);
    this.setVisible(true);
    Dimension size = new Dimension(600,600);
    this.setMinimumSize(size);
    this.setSize(size);
    this.setPreferredSize(size);
    _panel = new JPanel();
    this.add(_panel);

}

public static void main(String[] args) {
    Test t = new Test();
    String[] labels = {"label1", "label2","label3","label4","label5"};
    String[] fieldValues = {"value1","value2","value3","value4","value5"};
    t.createFields(labels,fieldValues);
}

private void createFields(String[] labels, String[] fieldValues) {
    _panel.setLayout(new GridBagLayout());
    int col = 0;
    int row = -1;
    for(int i=0; i < labels.length;i++) {
        JLabel label = new JLabel(labels[i] + ":", JLabel.TRAILING);
        JTextField field = new JTextField(fieldValues[i]);
        Dimension size = new Dimension(200,30);
        field.setPreferredSize(size);
        label.setLabelFor(field);


        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weighty = 1;
        c.weightx = 1;
        c.ipadx = 0;
        c.ipady = 0;
        c.insets = new Insets(0,0,0,0);
        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = col%4;
        if(i%2 == 0) row++;
        c.gridy = row;
        _panel.add(label,c);

        col++;
        c.gridx = col%4;
        _panel.add(field,c);
        col++;
    }

    this.setVisible(true);
}

最佳答案

如果您不介意元素位于面板中心(垂直和水平),请删除

    c.weighty = 1;
    c.weightx = 1;


从您的代码。
如果中心位置错误,请添加

    GridBagConstraints c = new GridBagConstraints();
    c.gridx=4;
    c.gridy=labels.length;
    c.weightx=1;
    c.weighty=1;
    _panel.add(new JLabel(),c);


循环后

关于java - 使GridBagLayout更紧凑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24041955/

10-10 04:00