2014-01-22 46 views
1

据我所知Swing Gridbag.gridwidth = 2;应该像HTML中的colspan一样工作,即强制一个列横过提供一列,在下一行中分成两列。Java Swing Gridbag面板不会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

任何帮助将是巨大的

+0

为了更好地帮助,请发布[MCVE](http://stackoverflow.com/help/mcve)。 –

+0

删除尽可能多的代码我可以 –

+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); 

通过添加合并单元格gbc在底部,它确保其设置也不会转移给其他人。

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

+0

很高兴你得到它排序。 :) –