Search code examples
javaswingjpaneljbutton

Add JButton to JPanel from Different Class


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.


Solution

  • 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