Java Swing Gridbag面板不会colspan

时间:2014-01-22 09:10:00

标签: java swing html-table layout-manager gridbaglayout

据我所知,Swing Gridbag.gridwidth = 2;应该像HTML中的colspan一样工作,强制列延伸提供一个列,在下一行分隔成两个等等

然而,我似乎正在压缩它下面的两根柱子,迫使它们彼此叠加。

public class MainClass extends JFrame {

public static void main(String args[]) {

    new MainClass();

}

public MainClass() {

    JPanel panel = new JPanel(new GridBagLayout());
    this.getContentPane().add(panel);

    final JTextField nameInput = new JTextField();

    final JLabel headerImage = new JLabel("test");

    final JTextField volunteerID = new JTextField();

    TitledBorder nameLabel;
    nameLabel = BorderFactory.createTitledBorder("Name");
    nameInput.setBorder(nameLabel);

    TitledBorder fileNameLabel;
    fileNameLabel = BorderFactory.createTitledBorder("Volunteer ID/ FileName");
    volunteerID.setBorder(fileNameLabel);


    JPanel constructorPanel = new JPanel();
    constructorPanel.add(nameInput);

    JPanel resultsPanel = new JPanel();
    resultsPanel.add(volunteerID);

    JPanel imagePanel = new JPanel();
    imagePanel.add(headerImage);

    GridBagConstraints gbc = new GridBagConstraints();

    // Constructors

    [[additional code]] //see below

    gbc.gridx = 0;
    gbc.gridy = 1;
    panel.add(constructorPanel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.NORTH;
    panel.add(resultsPanel, gbc);


    nameInput.setColumns(15);
    volunteerID.setColumns(15);

    this.pack();
    this.setTitle("GiGgle Pics Settings Constructor");
    this.setVisible(true);
    this.setResizable(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

以上产生以下内容:

enter image description here

但是,当我在上面标有[[附加代码]]的空格中添加以下代码时

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        gbc.fill = WIDTH;
        panel.add(imagePanel, gbc);

我明白了:

enter image description here

任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

找到它,

我向GridBagLayout添加组件的顺序是打赌它

    gbc.gridx = 0;
    gbc.gridy = 1;
    panel.add(constructorPanel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.NORTH;
    panel.add(resultsPanel, gbc);

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    panel.add(imagePanel, gbc);

通过在底部添加colspan gbc,可确保其设置不会转移到其他设置。

另一种解决方案是重置gbc.gridwidth = 2;在每个