如何制作JCheckBoxes列表并将其放入JScrollPane

时间:2016-11-02 22:17:26

标签: java swing jscrollpane jcheckbox

我正在尝试制作一些JCheckBoxes列表并将其放在滚动窗格内。

我尝试创建一系列复选框并将其放在JList中,然后放在JScrollPane中,但它只打印一些关于方法复选框的信息。

我想实现这样的目标:

enter image description here

到目前为止,这是我的代码:

public class MainFrame extends JFrame
{
private JPanel panel = new JPanel();
private JScrollPane scroll;

public MainFrame()
{
    add();
    setTitle("Dropable checkbox");
    setSize(500, 500);

    add(panel);

    setVisible(true);
}

private void add()
{
    String categories[] = { "Household", "Office", "Extended Family",
            "Company (US)", "Company (World)", "Team", "Will",
            "Birthday Card List", "High School", "Country", "Continent",
            "Planet","KITA" };

    JPanel p = new JPanel();
    BoxLayout layout = new BoxLayout(p, BoxLayout.Y_AXIS);
    p.setLayout(layout);

    for (String string : categories) {
        p.add(new JCheckBox(string));
    }

    JScrollPane scroll = new JScrollPane(p);
    panel.add(scroll);
}

}

这就是我的屏幕现在的样子

enter image description here

1 个答案:

答案 0 :(得分:0)

您应该将变量和方法重命名为Java标准,因为您似乎已经混淆了自己。

例如,您要创建滚动面板2次(一次在顶部,一次在底部)。此外,不需要面板p。此外,您不应按照创建方式创建滚动窗格。

我已经创建了一个工作程序,但是我使用了MigLayout,因为我不太了解BoxLayout,但你应该看到这一点并理解如何创建的重要部分滚动窗格。

public class MainFrame extends JFrame {
    private JPanel panel = new JPanel();
    JScrollPane scroll = new JScrollPane();

    public MainFrame() {
        createUI();
        setTitle("Dropable checkbox");
        setSize(300, 400);
        setVisible(true);
    }

    private void createUI() {
        String categories[] = { "Household", "Office", "Extended Family", "Company (US)", "Company (World)", "Team",
                "Will", "Birthday Card List", "High School", "Country", "Continent", "Planet", "KITA" };

        setLayout(new MigLayout());
        panel.setLayout(new MigLayout("wrap 1"));

        for (String string : categories) {
            panel.add(new JCheckBox(string));
        }
        scroll.setViewportView(panel);
        add(scroll);
    }

    public static void main(String[] args) {
        MainFrame mf = new MainFrame();
        mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mf.setLocationRelativeTo(null);
    }
}