[英]Add JButton to JPanel from Different Class
嗨,有一種方法可以將JButton從不同的類添加到JPanel。 因此,基本上,JPanel在Class A
而JButton在Class B
如何將按鈕放在另一個類的Panel上。 希望如果您需要我澄清,請告訴我。 我在這里先向您的幫助表示感謝。
您可以進行如下操作:
public OtherClass {
public JButton getButton (){
JButton b = new JButton();
b.set...();
b.set...();
b.set...();
b.set...();
return b;
}
}
然后,您可以使用此函數創建一個始終相同的JButton。
另一個選擇是將Button創建為靜態對象,並在OtherClass中使用它,這不是一個很好的解決方案,但是可以選擇
您將需要類A中的類B的實例對象訪問其變量和方法。 然后,您可以編寫如下內容:
public ClassB {
public JButton getButton() {
return myJButton;
}
}
另一種方法是在類B中使JButton靜態,但這是一個骯臟的技巧,是一種不良的設計模式。
public ClassB {
public static JButton myJButton;
}
然后,您可以使用ClassB.myJButton
從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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.