我正在尝试创建一个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);
答案 0 :(得分:1)
首先,使用默认构造函数创建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);