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!
You have reference to centerPanel in your main method. After you invoke
centerPanel.renderPanel();
the buttons will be added to the 'center' reference of typeJPanel
in CenterPanel instance. You can get the reference of 'center' by invokingcenterPanel.getGUI();
in main method.This will return thecenter
reference of typeJComponent
. JComponent is a awt container.so, you can callcenter.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.Make the buttons members of
CenterPanel