1

Hi is there a way to Add JButton to JPanel from Different Class. So basically the JPanel is in a Class A and JButton is in a Class B how can I put the button on the Panel which is in a different class. Hopefully this makes sense if you need me to clarify let me know. Thanks for the help in advance.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Navleen Singh
  • 155
  • 2
  • 11

3 Answers3

0

You can make something like this:

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

Then you can use this function to create a JButton which is always the same.

Another option is to create your Button as a static and use it in your OtherClass, this is not a well solution, but it can be an option

roeygol
  • 4,908
  • 9
  • 51
  • 88
0

You would need the instance object of class B in class A to access its variables and methods. You could then write something like the following:

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

Another way to do it is to make the JButton static in class B, however this is a dirty hack that is a bad design pattern.

public ClassB {
    public static JButton myJButton;
}

You could then access the JButton from ClassA by using ClassB.myJButton

Thugald
  • 1
  • 1
0

You can Inherit classes or use a single one:

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;
}

}

}

Ramses Asmush
  • 134
  • 1
  • 4
  • 10