我試過所有的組合,看了看所有的文檔,但我無法弄清楚如何使用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);
在此先感謝大家,對不起,這個愚蠢的問題!
我現在試試這個,謝謝 – Cristian
現在工作好多了,謝謝! – Cristian