2013-04-29 87 views
-1

我是新来的Java UI和我有这个基本的问题:自定义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); 

,但它不是working.It不是增加什么UI.while下面的代码是可以正常使用:

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); 
+1

您不添加您的组件(复选框,标签,按钮)到您的自定义组件。 (在创建它们之后调用'this.add(label);' – Breavyn 2013-04-29 07:30:57

+0

@ColinGillespie这需要一个答案! – MadProgrammer 2013-04-29 07:32:03

+1

*“我是java UI的新手,我有这个基本问题:”*您的问题是什么?想想2或3可能适用,但你选择一个并添加它作为[编辑问题](http://stackoverflow.com/posts/16273322/edit)。 – 2013-04-29 07:53:28

回答

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

@AndrewThompson但我的错误代码虽然:'添加(标签);'是不正确的,并且必须是'add(this.label);'。固定。谢谢观看。:-) – 2013-04-29 08:00:49

+0

现在看起来很不错。 :) – 2013-04-29 08:01:42