简体   繁体   中英

Card Layout showing wrong panel

One panel is added through method where card layout is. And another is passed to a method through the object. The problem is that the Panel of a card Layout is showing panel "1" instead of panel "2",like panel "2" is not even passing to a method. There are no errors....

I tried to simplify code as much as i could:

First class:

     public class Game  extends JFrame {
          private CardLayout cl;
          private JPanel MAIN;
          private JPanel FIRST;

          public Game(){

          FIRST = new JPanel();
          FIRST.setLayout(new BorderLayout());

          cl = new CardLayout();
          MAIN = new JPanel();

          MAIN.setLayout(cl);   

      }
          public void Show(){

            MAIN.add(FIRST, "1");
            cl.show(MAIN, "2");
            add(MAIN);  
      }


          public void addPanel2(JPanel panel){
            MAIN.add(panel, "2");   
      }
}

Second class:

public class meni {
   private JPanel SECOND;
   Game nova = new Game();

   public meni(){

      SECOND = new JPanel();
      SECOND.setLayout(new GridBagLayout());

      nova.addPanel2(SECOND);
   }
}

Main class:

  public static void main(String[] args){

      Game ticFrame = new Game();
      meni luk = new meni();

      ticFrame.show();

      ticFrame.setTitle("Hey");
      ticFrame.setSize(600,600);
      ticFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ticFrame.setLocationRelativeTo(null);
      ticFrame.setVisible(true);
   }
 }

You're adding your second JPanel just fine, but you're adding it to the wrong Game object. A Game object is currently visible on program start up, and within that second class you create a completely new and unique Game object and add your second JPanel to that, so it makes sense that it won't show in the visualized object.

Solution: Don't create a new Game object in the second class, but instead make sure that the second class has a valid reference to the visualized Game object. This can be done through a constructor parameter or a setter method parameter.

nova.addPanel2(SECOND); what do you mean from this code?? to add panel to frame we have methos such as JPanel.add( your panel object).

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