问题
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