Search code examples
javaswingclassjpaneljcomponent

Java Swing: Access panel components from another class


Hi i basically have two classes, one main and one just to separate the panels, just for code readability really.

i have :

public class Main{

   public static void main (String args[]) {
    JFrame mainJFrame;
    mainJFrame = new JFrame();

    //some other code here

    CenterPanel centerPanel = new CenterPanel();
    centerPanel.renderPanel();
    mainFrame.add(centerPanel.getGUI());

   }


}

class CenterPanel{
    JPanel center = new JPanel();

    public void renderPanel(){
        JButton enterButton = new JButton("enter");
        JButton exitButton = new JButton("exit");
        center.add(exitButton);
        center.add(enterButton);
    }

    public JComponent getGUI(){
        return center;
    }
}

Above code works perfectly. It renders the centerPanel which contains the buttons enter and exit. My question is:

I still need to manipulate the buttons in the main, like change color, add some action listener and the likes. But i cannot access them anymore in the main because technically they are from a different class, and therefore in the main, centerPanel is another object.

How do I access the buttons and use it (sets, actionlisteners, etc)? even if they came from another class and i still wish to use it inside the main?Many Thanks!


Solution

  • Make the buttons members of CenterPanel

    class CenterPanel{
        JPanel center = new JPanel();
    
        JButton enterButton;
        JButton exitButton;
    
        public void renderPanel(){
            enterButton = new JButton("enter");
            exitButton = new JButton("exit");
            center.add(exitButton);
            center.add(enterButton);
        }
    
        public JButton getEnterButton()
        {
           return enterButton;
        }
    
        public JButton getExitButton()
        {
           return exitButton;
        }
    
        public JComponent getGUI(){
            return center;
        }
    }