-1

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

我想创建一个自定义类,其中包含 3 个摆动组件,然后我想将此组件添加到 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");
    }
}

并将其添加到 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);

但它不起作用。它没有向 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);
4

1 回答 1

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);
    }
}
于 2013-04-29T07:32:30.920 回答