简体   繁体   中英

JPanel does not displayed on JFrame

Problem - the given codes below is not displaying my JPanel(PageOne) and I am not sure why is it not displaying my JPanel(PageOne). Please Help.

I have added the JPanel(PageOne) to my panel which has a cardLayout(); I have set my JFrame to visible already.

PageOne.java

   import javax.swing.JLabel;
   import javax.swing.JPanel;

   public class PageOne extends JPanel {

    public PageOne() {
         JLabel label = new JLabel("Page 1");
         JPanel panel = new JPanel();
         panel.add(label);
   }    }

PageTwo.java

   import javax.swing.JLabel;
   import javax.swing.JPanel;

   public class PageTwo extends JPanel {

    public PageTwo() {
         JLabel label = new JLabel("Page 2");
         JPanel panel = new JPanel();
         panel.add(label);
       }
   }

DisplayUI.java

   import java.awt.CardLayout;
   import javax.swing.JFrame;  
   import javax.swing.JPanel;
   import javax.swing.SwingUtilities;

   public class DisplayUI {

    public static void main(String[] args) {
           new DisplayUI();
    }

       public DisplayUI() {
           SwingUtilities.invokeLater(new Runnable() {
           @Override
               public void run() {
                  CardLayout cardLayout = new CardLayout();
                   JFrame frame = new JFrame("frame");
                   JPanel panel = new JPanel();
                   panel.setLayout(cardLayout);    
                   panel.add(new PageOne(), "1");
                   panel.add(new PageTwo(), "2");
                   cardLayout.show(panel,"1");
                   frame.add(panel);
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.pack();
                   frame.setLocationRelativeTo(null);
                   frame.setVisible(true);
               }
           });
       }
   }

You're not actually adding anything to PageOne or PageTwo panels...

public PageOne() {
    JLabel label = new JLabel("Page 1");
    JPanel panel = new JPanel();
    panel.add(label);
    // But nothing is actually added to "this"...
}

Unless you "really" need it, you can get rid of the second JPanel and add the label directly to PageOne (and the same thing goes for PageTwo )

public PageOne() {
    JLabel label = new JLabel("Page 1");
    add(label);
}

Or add the JPanel you create (which contains the label)

public PageOne() {
    JLabel label = new JLabel("Page 1");
    JPanel panel = new JPanel();
    panel.add(label);
    add(panel);
}

Remember, JPanel is type of Container , it can have child components.

Get the content pane of frame and than try adding :

Container container=frame.getContentPane();
container.add(panel);

Hope this helps you.

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