Michael
Michael

Reputation: 4461

Vertical alignment of checkboxes

Could you help me understand how to set left vertical alignment to the checkboxes. I mean each checkbox on its own row.

Tried everything I could imagine and have come to the end of my wit.

public class DisplayFrame extends JFrame {
    public DisplayFrame(ArrayList<String> contents){
        DisplayPanel panel = new DisplayPanel(contents, whiteList);
        add(panel);
    }

private void displayAll(){
        DisplayFrame frame = new DisplayFrame(contents, whiteList);
        GridBagLayout gbl = new GridBagLayout();
        frame.setLayout(gbl);
        frame.setVisible(true);
...
    }

public class DisplayPanel extends JPanel {
    ArrayList<JCheckBox> cbArrayList = new ArrayList<JCheckBox>();
    ArrayList<String> contents;

...
    public DisplayPanel(ArrayList<String> contents){
...
        createListOfCheckBoxes();
    }


    private void createListOfCheckBoxes() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = contents.size() + 1;
        gbc.gridheight = contents.size() + 1;
        for (int i = 0; i < contents.size(); i++){
            gbc.gridx = 0;
            gbc.gridy = i;
            String configuration = contents.get(i);
            JCheckBox currentCheckBox = new JCheckBox(configuration);
            if (whiteList.contains(configuration)){
                currentCheckBox.setSelected(true);
            }
            currentCheckBox.setVisible(true);
            add(currentCheckBox, gbc);
        }
    }

Upvotes: 0

Views: 1996

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208974

"If I were able to proceed without GridBagLayout, that would suit me"

You can just use a BoxLayout. Box is a convenience class for BoxLayout. You can just do

Box box = Box.createVerticalBox();
for (int i = 0; i < contents.size(); i++){
    String configuration = contents.get(i);
    JCheckBox currentCheckBox = new JCheckBox(configuration);
    if (whiteList.contains(configuration)){
        currentCheckBox.setSelected(true);
    }
    box.add(currentCheckBox);
}

Since Box is a JComponent, you can just add the box to a container.

You can see more at How to Use BoxLayout

Simple Example

import javax.swing.*;

public class BoxDemo {

    public static void main(String[] args) {
        Box box = Box.createVerticalBox();
        JCheckBox cbox1 = new JCheckBox("Check me once");
        JCheckBox cbox2 = new JCheckBox("Check me twice");
        JCheckBox cbox3 = new JCheckBox("Check me thrice");
        box.add(cbox1);
        box.add(cbox2);
        box.add(cbox3);
        JOptionPane.showMessageDialog(null, box);
    }
}

enter image description here

Upvotes: 2

Related Questions