簡體   English   中英

使用 GridBagLayout 格式化 JPanel

[英]Formatting JPanels with GridBagLayout

所以我正在為我作為頂點的小游戲創建一個 GUI。 我有 4 個 JPanel,我正在嘗試使用 GridBagLayout 在一個框架上定位。

它目前看起來像這樣:當前的 GUI 邏輯錯誤在此處輸入圖片說明

但我希望它在設計上與此更相似:對不起,油漆技能不好在此處輸入圖片說明

框架代碼:

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,即 6 個按鈕,應該像它們在糟糕的繪畫圖片中一樣,按鈕后面的白色區域與 4 個按鈕下面應該去怪物所在的地方,右邊的 JLabels 應該在右上角。 謝謝你的幫助

我不會通過你的代碼來試圖找出它為什么不起作用,我真的沒有時間,但像下面的例子似乎接近你正在尋找的東西

例子

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來產生相同的效果,但這只是我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM