Java Swing: Access panel components from another class

假如想象 提交于 2020-01-29 20:33:27

问题


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!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/19345445/java-swing-access-panel-components-from-another-class

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