GridBagLayout左对齐

时间:2014-04-19 15:41:47

标签: java swing alignment gridbaglayout

这是我的代码:

                JPanel panel = new JPanel();
                JPanel p = new JPanel(new GridBagLayout());
                p.setBackground(Color.green);
                GridBagConstraints c1 = new GridBagConstraints();
                c1.insets = new Insets(0, 0, 0, 0);
                c1.anchor = GridBagConstraints.WEST;
                int index = 0;
                int i2 = 0;
                for(String[] data : attribute.choices){
                    JCheckBox checkbox = new JCheckBox(data[0]);
                    checkbox.setBackground(Color.red);
                    checkbox.setSelected(false);
                    c1.gridx = index % 2;
                    c1.gridy = index / 2;
                    p.add(checkbox, c1);
                    index++;
                }
                panel.add(p);

这就是结果:

enter image description here

我想要右边的复选框(红色区域)。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

  

我想要右边的复选框(红色区域)。

默认情况下,面板使用“居中对齐”的FlowLayout。您可以将对齐方式更改为right aligned

//panel.add(p);
panel.setLayout( new FlowLayout(FlowLayout.RIGHT) );
panel.add(p);