2016-04-16 55 views
-1

因此,我正在爲一款我正在製作的頂級小遊戲創建GUI。我有4個JPanels,我試圖使用GridBagLayout在一幀上定位。使用GridBagLayout格式化JPanels

目前,它看起來像這樣: Current GUI Logic Error enter image description here

但我想它在設計上這更類似:Sorry for Bad Paint Skills enter image description here

代碼框架:

public OverlordFrame() 
{ 
    buttonPanel = new ButtonPanel(); 
    invPanel = new InventoryPanel(); 
    statPanel = new PlayerStatsPanel(invPanel); 
    monstPanel = new MonsterPanel(); 

    this.setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 

    c.ipadx = 10; 
    c.ipady = 50; 


    c.gridx = 0; 
    c.gridy = 0; 
    c.weightx = .1; 
    c.weighty = .4; 
    c.gridheight = 2; 
    c.fill = GridBagConstraints.VERTICAL; 
    c.anchor = GridBagConstraints.LINE_START; 
    this.add(invPanel, c); 


    c.gridx = 1; 
    c.gridy = 1; 
    c.weightx = .4; 
    c.weighty = .3; 
    c.gridwidth = 2; 
    c.gridheight = 0; 
    c.fill = GridBagConstraints.NONE; 
    c.anchor = GridBagConstraints.CENTER; 
    this.add(buttonPanel, c); 


    c.gridx = 2; 
    c.gridy = 0; 
    c.weightx = .1; 
    c.weighty = .4; 
    c.gridwidth = 0; 
    c.anchor = GridBagConstraints.LINE_END; 
    this.add(statPanel, c); 


    c.gridx = 1; 
    c.weightx = .4; 
    c.weighty = .4; 
    c.anchor = GridBagConstraints.CENTER; 
    this.add(monstPanel, c); 


    this.setSize(1440, 810); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setVisible(true); 
} 

注意:左側的空白區域是InventoryPanel,也就是正確的位置,ButtonPanel,wh ich是6個按鈕,應該像它們在壞顏料圖片中那樣去掉,帶有4個按鈕的按鈕後面的白色區域應該到達怪物所在的位置,並且右側的JLabels應該位於右上角。感謝您的任何幫助

+0

你的兩個圖像不要」看起來很像,就像蘋果和蘋果橙子給我。請澄清。 –

+0

@HovercraftFullOfEels這是問題所在,我試圖讓它看起來更像是塗料照片,但我無法使格式化起作用 –

回答

1

我沒有通過你的代碼試圖找出它爲什麼不工作,我沒有時間,但像下面的例子似乎接近你是什麼尋找

Example

public class TestPane extends JPanel { 

    public TestPane() { 
     setLayout(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridx = 0; 
     gbc.gridy = 0; 
     gbc.gridheight = 2; 
     gbc.weightx = 0.3; 
     gbc.weighty = 1; 
     gbc.fill = GridBagConstraints.BOTH; 
     add(makePane(Color.BLUE), gbc); 

     gbc.gridx = 1; 
     gbc.gridy = 0; 
     gbc.gridheight = 1; 
     gbc.weightx = 0.4; 
     gbc.weighty = 0.5; 
     add(makePane(Color.MAGENTA), gbc); 

     gbc.gridx = 2; 
     gbc.weightx = 0.1; 
     add(makePane(Color.YELLOW), gbc); 

     gbc.gridx = 1; 
     gbc.gridy = 1; 
     gbc.gridwidth = 2; 
     gbc.weightx = 0.7; 
     gbc.weighty = 0.5; 
     gbc.fill = GridBagConstraints.BOTH; 
     add(makePane(Color.CYAN), gbc); 
    } 

    protected JPanel makePane(Color color) { 
     JPanel panel = new JPanel(); 
     panel.setBackground(color); 
     return panel; 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(200, 200); 
    } 

} 

說了這麼多,我可能會嘗試使用一系列化合物BorderLayout s到產生同樣的效果,但是這只是我

+0

非常感謝! –

+0

@LarryKruz如果您認爲這有幫助,請按接受的方式回答。 –