[英]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.
它呈现包含输入和退出按钮的centerPanel。 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.
但是我无法再在主目录中 访问它们,因为从技术上讲它们是来自不同的类,因此在主目录中,centerPanel是另一个对象。
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!
即使他们来自另一个班级并且我仍然希望在主要课程中使用它?非常感谢!
Make the buttons members of CenterPanel
使按钮成为
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. 您在主要方法中引用了centerPanel。 After you invoke
centerPanel.renderPanel();
调用
centerPanel.renderPanel();
the buttons will be added to the 'center' reference of type JPanel
in CenterPanel instance. 这些按钮将被添加到CenterPanel实例中
JPanel
类型的'center'引用中。 You can get the reference of 'center' by invoking centerPanel.getGUI();
您可以通过调用
centerPanel.getGUI();
获取“ center”的引用centerPanel.getGUI();
in main method.This will return the center
reference of type JComponent
. 在main方法中。这将返回
JComponent
类型的center
引用。 JComponent is a awt container.so, you can call center.getComponents()
. JComponent是awt容器。因此,您可以调用
center.getComponents()
。 This will return all the components in an array present in the JPanel. 这将返回JPanel中存在的数组中的所有组件。 ie center reference.
即中心参考。 You can iterate them, get their type and do whatever you want.
您可以迭代它们,获取它们的类型,然后执行所需的任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.