2015-02-17 85 views
1

嗨有没有办法从不同的类添加JButton到JPanel。所以基本上JPanel在Class A和JButton在Class B我怎么能把按钮放在不同类的面板上。希望这是有道理的,如果你需要我澄清让我知道。我在这里先向您的帮助表示感谢。将JButton添加到来自不同类的JPanel

回答

0

你可以让这样的事情:

public OtherClass { 
    public JButton getButton(){ 
     JButton b = new JButton(); 
     b.set...(); 
     b.set...(); 
     b.set...(); 
     b.set...(); 
     return b; 
    } 
} 

然后你就可以使用这个功能来创建了一个JButton这始终是相同的。

另一种选择是创建按钮为静态,并在您OtherClass使用它,这不是一个很好的解决方案,但它可以是一种选择

0

您需要B类的实例对象A类访问其变量和方法。然后,您可以编写类似以下内容:

public ClassB { 
    public JButton getButton() { 
     return myJButton; 
    } 
} 

另一种方式来做到这一点是让JButton的B类静态的,但是这是一个肮脏的黑客是一个不好的设计模式。

public ClassB { 
    public static JButton myJButton; 
} 

然后,您可以通过使用ClassB.myJButton

0

可以继承类或者使用一个单一的一个访问来自ClassA的将JButton:

public class Example{ 

public static void main(String []args){ 

    JFrame wnd = new JFrame(); 
    //edit your frame... 
    //... 
    wnd.setContentPane(new CustomPanel()); //Panel from your class 
    wnd.getContentPane().add(new CustomButton()); //Button from another class 

    //Or this way: 

    wnd.setContenPane(new Items().CustomPanel()); 
    wnd.getContentPane().add(new Items().CustomButton()); 

} 

static class CustomButton extends JButton{ 

    public CustomButton(){ 
    //Implementation... 
    setSize(...); 
    setBackground(...); 
    addActionListener(new ActionListener(){ 
    //.... 
    }); 
    } 

} 

static class CustomPanel extends JPanel{ 

    public CustomPanel(){ 
    //Implementation... 
    setSize(...); 
    setBackground(...); 
    OtherStuff 
    //.... 
    } 

} 

static class Items{ 

public JButton CustomButton(){ 
JButton button = new JButton(); 
//Edit your button... 
return button; 
} 

public JPanel CustomPanel(){ 
JPanel panel = new JPanel(); 
//Edit your panel... 
return panel; 
} 

} 

}