我是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");
}
}
要将其添加到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);
答案 0 :(得分: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);
}
}