简体   繁体   中英

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:

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. 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.

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.

This will be , just remove the instance called 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());
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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