2012-08-06 69 views
0

我正在使用帶有GridBagLayout的JDialog。由於此佈局自動確定容器和組件的大小,所以我沒有在任何東西上使用setSize。但是,當繪製GUI時,似乎不必要地拉伸容器。GridBagLayout如何確定容器的大小

爲什麼GridBagLayout不能根據需要調整容器大小?基本上我希望對話框的大小和內部的表一樣大。以下是代碼片段:

public class GridBagLayoutTester 
{ 

public static void main(String[] args) 

{ 

JDialog mDialog = new JDialog(); 

    JPanel panel1 = new JPanel(); 
    panel1.setLayout(new GridBagLayout()); 

    // Create a table to be added to the panel 
    JTable table = new JTable(4,4); 
    JScrollPane scrollpane = new JScrollPane(table); 
    scrollpane.setBorder(BorderFactory.createLineBorder(Color.ORANGE, 5)); 

    GridBagConstraints gbc = new GridBagConstraints(); 
    gbc.gridx = gbc.gridy = 0; 
    gbc.fill = GridBagConstraints.NONE; 
    gbc.anchor = GridBagConstraints.FIRST_LINE_START; 

    // Add table to the panel 
    panel1.add(scrollpane, gbc); 

    mDialog.add(panel1, BorderLayout.CENTER); 

    // Display the window. 
    mDialog.pack(); 
    mDialog.setVisible(true); 
    } 
} 

回答

0

當默認大小不是您想要的大小時,您必須設置組件的首選大小。

改變你的程序中加入這些行:

// Display the window. 
    mDialog.pack(); 
    Dimension d = table.getPreferredSize(); 
    d.width += 16; 
    d.height += 10; 
    scrollpane.setPreferredSize(d); 
    mDialog.pack(); 
    mDialog.setVisible(true); 

16的額外寬度可容納邊框和垂直滾動條。

附加高度爲10可容納邊框。

+0

工作就像一個魅力。謝謝 ! – Sandhya 2012-08-15 07:00:50