且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 GridBagLayout 强制 JPanel 使用 JFrame 调整大小

更新时间:2023-12-05 11:19:28

您的问题是您使用 menuPanel 将 GridBagLayout 添加到 Display JPanel 中,后者使用 JPanel 的默认 FlowLayout.FlowLayout 不会调整添加到其中的组件的大小.解决方案:去掉menuPanel,只使用Display JPanel.给它一个 GridBagLayout 并向其添加组件.

Your problem is that you're adding your GridBagLayout using menuPanel into the Display JPanel, the latter of which uses JPanel's default FlowLayout. FlowLayout will not resize components added to it. The solution: get rid of menuPanel and just use the Display JPanel. Give it a GridBagLayout and add the components to it.

在你的 Display 构造函数中也有

so have within your Display's constructor

setLayout(new GridBagLayout());

删除 JPanel menuPanel = new JPanel(); 和任何你有 menuPane.add(...); 的地方,把它改成简单的 add(...);

delete the JPanel menuPanel = new JPanel(); and anywhere you have menuPane.add(...);, change it to simply add(...);

例如,

public class Display extends JPanel{    
    public Display(){
        // !! menuPanel = new JPanel(new GridBagLayout());
        GridBagConstraints con = new GridBagConstraints();

        mainMenuImageP = new JPanel();
        mainMenuImageP.setBackground(Color.BLACK);
        con.fill = GridBagConstraints.BOTH;
        con.gridy = 0;
        con.gridx = 0;
        con.gridwidth = 2;
        con.weightx = 0.5;
        con.weighty = 0.5;
        con.anchor = GridBagConstraints.CENTER;
        con.ipadx = 400;
        con.ipady = 300;
        con.insets = new Insets(0,20,0,20);
        // !! menuPanel.add(mainMenuImageP, con);
        add(mainMenuImageP, con); // !!

        newGameB = new JButton("New Game");
        con.fill = GridBagConstraints.HORIZONTAL;
        con.gridy = 1;
        con.gridx = 0;
        con.gridwidth = 1;
        con.weightx = 0.5;
        con.weighty = 0.5;
        con.anchor = GridBagConstraints.CENTER;
        con.ipadx = 0;
        con.ipady = 0;
        con.insets = new Insets(10,10,10,10);
        // !! menuPanel.add(newGameB, con);
        add(newGameB, con); // !!

        loadGameB = new JButton("Load Game");
        con.fill = GridBagConstraints.HORIZONTAL;
        con.gridy = 1;
        con.gridx = 1;
        con.gridwidth = 1;
        con.weightx = 0.5;
        con.weighty = 0.5;
        con.anchor = GridBagConstraints.CENTER;
        con.ipadx = 0;
        con.ipady = 0;
        con.insets = new Insets(10,10,10,10);
        // !! menuPanel.add(loadGameB, con);
        add(loadGameB, con); // !!

        // !! add(menuPanel);
    }

}

请注意,如果这没有帮助,请考虑创建并发布最小示例程序SSCCE.

Note that if this doesn't help, then please consider creating and posting a minimal example program or SSCCE.