java swing中的自定义UI组件

vis*_*esh -1 java swing

我是java UI的新手,我有这个基本问题:

我想创建一个自定义类,其中包含3个swing组件,然后我想将这些组件添加到UI中.

class ListItem extends JComponent{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    JCheckBox checkbox;
    JLabel label;
    JButton removeBtn;

    public ListItem(String label) {
        this.label = new JLabel();
        this.label.setText(label);

        this.checkbox = new JCheckBox();

        this.removeBtn = new JButton();
        removeBtn.setText("Remove");
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到UI我这样做:

panelContent = new JPanel(new CardLayout());
this.add(panelContent, BorderLayout.CENTER); //some class which is added to UI

ListItem mItem = new ListItem("todo item 1");
panelContent.add(mItem);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.它没有向UI添加任何内容.而以下代码完美地运行:

panelContent = new JPanel(new CardLayout());
this.add(panelContent, BorderLayout.CENTER); //some class which is added to UI

JLabel lab = new JLabel();
lab.setText("label");
panelContent.add(lab);
Run Code Online (Sandbox Code Playgroud)

Gui*_*let 5

问题是您永远不会将组件添加ListItem到组件本身.而且,JComponent没有任何默认值LayoutManager,所以你需要设置一个.

可能是这样的:

class ListItem extends JComponent{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    JCheckBox checkbox;
    JLabel label;
    JButton removeBtn;

    public ListItem(String label) {
        setLayout(new BorderLayout());
        this.label = new JLabel();
        this.label.setText(label);

        this.checkbox = new JCheckBox();

        this.removeBtn = new JButton();
        removeBtn.setText("Remove");
        add(checkbox, BorderLayout.WEST);
        add(this.label);
        add(removeBtn, BorderLayout.EAST);
    }
}
Run Code Online (Sandbox Code Playgroud)