2012-10-20 59 views
0

我試過所有的組合,看了看所有的文檔,但我無法弄清楚如何使用GridBagLayout。GridBagLayout幫助

我在JPanel中有3個組件,GridBagLayout是JPanel的LayoutManager,在這3個組件上使用GridBagConstraints。

使用當前代碼(如下所示),3個元素正確顯示在面板上。問題是第一個組件是JLabel,有時很長,如果是這種情況,那麼它會擴展並使其他兩個組件變小。

我的目標是讓JPanel具有1行4列的GridBagLayout,其中第一個元素佔據前2列,其餘2個元素佔用剩餘的2個元素,並且這些元素不需要擴大他們的專欄。

private static void setConstraints(GridBagConstraints constraints, int gridx, int gridy, int weightx, Insets insets) { 
    constraints.gridx = gridx; 
    constraints.weightx = weightx; 
    constraints.insets = insets; 
} 

gridBagLayout = new GridBagLayout(); 
constraints = new GridBagConstraints(); 
centerPanel = new JPanel(gridBagLayout); 

constraints.fill = GridBagConstraints.HORIZONTAL; 
fileNameLabel = new JLabel("Resolving: '" + EngineHelpers.trimStringToFitPanel(urlTextField.getText(), 70) + "'"); 
setConstraints(constraints, 0, 0, 2, new Insets(0, 5, 5, 0)); 
gridBagLayout.setConstraints(fileNameLabel, constraints); 
progressBar = new JProgressBar(); 
progressBar.setStringPainted(true); 
setConstraints(constraints, 1, 0, 1, new Insets(0, 5, 5, 0)); 
gridBagLayout.setConstraints(progressBar, constraints); 
cancelDownloadButton = new JButton("Cancel"); 
setConstraints(constraints, 2, 0, 1, new Insets(0, 0, 0, 0)); 
gridBagLayout.setConstraints(cancelDownloadButton, constraints); 

centerPanel.add(fileNameLabel); 
centerPanel.add(progressBar); 
centerPanel.add(cancelDownloadButton); 

在此先感謝大家,對不起,這個愚蠢的問題!

回答

2

對於按鈕和進度條,您可能需要將weightx設置爲0。對於標籤,將權重設置爲1.這將保持按鈕和進度條不會展開,並讓進度條佔據所有額外空間。

還設置gridwidth上的進度條約束爲2,所以它實際上使用2列。

最後,根據放置的位置,它可能不會實際擴大以填充容器。如果將centerPanel放置在具有BorderLayout的父級中,則它應該展開。爲了確保,你可以添加一個邊界centerPanel.setBorder(BorderFactory.createLineBorder(Color.RED))進行調試。這對於按鈕,標籤和進度條也是有用的。

+0

我現在試試這個,謝謝 – Cristian

+0

現在工作好多了,謝謝! – Cristian