Java Swing: Access panel components from another class

浪子不回头ぞ 提交于 2019-12-01 10:29:36

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

You have reference to centerPanel in your main method. After you invoke centerPanel.renderPanel(); the buttons will be added to the 'center' reference of type JPanel in CenterPanel instance. You can get the reference of 'center' by invoking centerPanel.getGUI(); in main method.This will return the center reference of type JComponent. JComponent is a awt container.so, you can call center.getComponents(). This will return all the components in an array present in the JPanel. i.e. center reference. You can iterate them, get their type and do whatever you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!