简体   繁体   English

将另一个实例的面板实例添加到父面板

[英]Adding an instance of a panel from another class to a parent panel

Is something wrong with the construction of this class? 此类的构造有问题吗? I am trying to add an instance of it to a JPanel in another class: 我正在尝试将其实例添加到另一个类的JPanel中:

public class calculator2 extends JPanel {
     public calculator2() {
         JPanel x = new JPanel();
         x.setLayout(new GridLayout(0,5));

         x.add(new JLabel());
         x.add(new JButton("<<"));
         x.add(new JLabel());
         x.add(new JButton(">>"));
         x.add(new JLabel());
     }
}

This is what I am trying to use it on: 这就是我想在以下方面使用的功能:

    calculator2 test = new calculator2();
    JPanel panel3 = new JPanel(new BorderLayout());
    panel3.add(test, BorderLayout.SOUTH);

I dont get any type of run time error,it just dosen't show up. 我没有任何类型的运行时错误,只是没有出现。 When I put the code from the calculator2 class in the same class I am using in the second portion of code it shows up. 当我将Calculator2类中的代码放在同一类中时,将在代码的第二部分中使用它。 Thank you for your consideration. 谢谢您的考虑。

This is actually just an example, I have a full class with about 25 components using actionlisteners and the like and wanted to add it to a panel using the above method. 这实际上只是一个例子,我有一个使用动作侦听器等的大约25个组件的完整类,并希望使用上述方法将其添加到面板中。

Here you are just creating the panel without adding it anywhere to be seen. 在这里,您只是在创建面板,而无需将其添加到任何可见的地方。 Try using the parents methods inherited from JPanel instead of creating a new instance of another JPanel in the constructor. 尝试使用从JPanel继承的parent方法,而不是在构造函数中创建另一个JPanel的新实例。

This will be , just remove the instance called x. 这将是,只需删除名为x的实例。

public class calculator2 extends JPanel {
  public calculator2() {
     super();
     setLayout(new GridLayout(0,5));

     add(new JLabel());
     add(new JButton("<<"));
     add(new JLabel());
     add(new JButton(">>"));
     add(new JLabel());
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM