Im將JFrame的內容窗格設置爲我創建的面板。該面板爲其後面板使用Grid Bag Layout
。我把這個佈局像這樣:用面板填充內容窗格
private void initPanel() {
setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
populateGUI();
}
這將導致「遊戲」喜歡這樣的:
什麼實際上,我試圖做的是擴大這些面板(微小正方形)。 JFrame的尺寸爲800 x 500,因此每個面板應該佔用100 x 100,共40個面板。問題在於面板太小了。
我填充JFrame的內容窗格(通過自己的面板更換 - 紅色標記)使用此代碼:
private void populateGUI() {
// Fill the frame with panels
for (int rowPos = 0; rowPos < numColumns; rowPos++) {
for (int colPos = 0; colPos < numRows; colPos++) {
constraints.gridx = rowPos;
constraints.gridy = colPos;
// Add component
add(new GameDummyPanel(gameUtil.generateRandomColour(),
panelWidth, panelHeight), constraints);
}
}
}
注 - 這些都是我實現的唯一約束。在GameDummyPanel類中,我使用以下設置大小:
public GameDummyPanel(Color panelColor, int panelWidth, int panelHeight)
{
dummyPanelWidth = panelWidth/8;
dummyPanelHeight = panelHeight/5;
setBackground(panelColor);
setSize(new Dimension(dummyPanelWidth, dummyPanelHeight));
}
那麼爲什麼這不被執行?它不像我在面板和作爲JFrame的內容窗格的面板上調用pack。
感謝
更新
審查和執行什麼需要做的答案 - 你不應該想下面看 - 是的約束上的fill
屬性設置爲BOTH
並刪除所有基於面板類的基於尺寸的屬性。這意味着我的約束是這樣的:
constraints = new GridBagConstraints();
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.BOTH;
減去各自成立gridx
和gridy
面板的真正獨特的定位。那麼JPanel的實現可能實際上被淘汰,並且讓JPanel在運行中剛剛創建。
這個帖子可能會幫助:HTTP: //stackoverflow.com/questions/1783793/java-difference-between-the-setpreferredsize-and-setsize-methods-in-compone –