Java GridBagLayout 组件在背景填充时居中

Java GridBagLayout components centering when background filled

我正在尝试创建一个 GridBagLayout,我已经按照我的需要设置了面板。但是,我不能在不强制所有组件居中的情况下设置每个面板的背景颜色。

这里的面板是彩色的,但所有组件都居中 http://i.imgur.com/BattBdw.png


此处所有组件都按照代码中指定的方式对齐 NORTHWEST,但背景颜色未填充窗格。 http://i.imgur.com/lvuEy4u.png


对不起,我不能嵌入图片,我的声誉不够高:(



    GridBagConstraints GBC = new GridBagConstraints();
    GBC.fill = GridBagConstraints.BOTH;
    GBC.anchor = GridBagConstraints.NORTHWEST;



    //green panel
    GBC.gridx = 0;
    GBC.gridy = 0;
    GBC.weightx = 0.1;
    GBC.weighty = 0.1;      

    JPanel panelGreen = new JPanel();
    panelGreen.setBackground(Color.green);          

    //add button to green panel
    JButton button = new JButton("Button");
    panelGreen.add(button, GBC);

    contentPane.add(panelGreen, GBC);



    //blue panel
    GBC.gridx = 1;
    GBC.gridy = 0;
    GBC.weighty = 0.1;  
    GBC.weightx = 0.9;      

    JPanel panelBlue = new JPanel();
    panelBlue.setBackground(Color.blue);        
    contentPane.add(panelBlue, GBC);




    //red panel
    GBC.gridx = 0;
    GBC.gridy = 1;      
    GBC.weighty = 0.8;
    GBC.weightx = 0.1;

    JPanel panelRed = new JPanel();
    panelRed.setBackground(Color.red);  
    contentPane.add(panelRed, GBC);



    //black panel
    GBC.gridx = 0;
    GBC.gridy = 2;      
    GBC.weighty = 0.1;
    GBC.weightx = 0.1;
    GBC.gridwidth =2;   

    JPanel panelBlack = new JPanel();
    panelBlack.setBackground(Color.black);          
    contentPane.add(panelBlack, GBC);




    //yellow panel
    GBC.gridx = 1;
    GBC.gridy = 1;      
    GBC.weighty = 0.8;
    GBC.weightx = 0.9;
    GBC.gridwidth =1;   

    JPanel panelYellow = new JPanel();
    panelYellow.setBackground(Color.yellow);        
    contentPane.add(panelYellow, GBC);

首先,使用默认构造函数创建 JPanel() 意味着它会获得 FlowLayout - 您需要告诉您的面板使用 GridBagLayouts:

JPanel panelGreen = new JPanel(new GridBagLayout());

除此之外,您只需要在添加 JButton 时将 "fill" 属性 设置为 NONE,否则它会展开以填满整个窗格。添加按钮后,您可以为面板本身将其设置为 BOTH:

GBC.fill = GridBagConstraints.NONE;
JButton button = new JButton("Button");
panelGreen.add(button, GBC);

GBC.fill = GridBagConstraints.BOTH;
contentPane.add(panelGreen, GBC);