简体   繁体   中英

GridBagLayout align left

This is my code:

                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);

And this is the result:

在此处输入图片说明 .

I want the checkbox (the red area) alinged to the right. How can I do this?

I want the checkbox (the red area) alinged to the right.

By default a panel uses a "center aligned" FlowLayout. You can change the alignment to be right aligned .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM