垂直对齐复选框

时间:2014-04-06 16:33:59

标签: java swing

您能否帮我理解如何将左侧垂直对齐设置为复选框。我的意思是每个复选框都在它自己的行上。

尝试了我能想象到的一切,并且已经结束了我的智慧。

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

1 个答案:

答案 0 :(得分:2)

  

&#34;如果我能够在没有GridBagLayout的情况下继续进行,那将适合我&#34;

您可以使用BoxLayoutBoxBoxLayout的便利类。你可以做到

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

由于BoxJComponent,您只需将box添加到容器中即可。

您可以在How to Use BoxLayout

查看更多内容

简单示例

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