2014-01-22 44 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

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