Using CardLayout for multiple JPanels and nothing displays

冷暖自知 提交于 2019-12-02 12:00:48
MadProgrammer

First...

You need to create an instance of CardLayout BEFORE you apply it to the container and before add any components...

    cl = new CardLayout();
    contentPane.setLayout(cl);

Second...

You should be using the add(Component, Object) method

contentPane.add(mainPage, "1");

Third

public static void go() {

    JFrame frame = new JFrame();
    frame.setVisible(true);
}

Does nothing but creates an empty frame with nothing in it. It might be helpful to actually use MainProject, since it extends from JFrame

Fourth...

Don't extend directly from JFrame, you're not adding any new functionality to the class, it locks you into single use cases and it cause problems like the one you're having.

Instead, consider starting with a JPanel instead...

public class MainProject extends JPanel {

(ps- This change may cause other compiler errors, which I'm not going to try and fix here)

Then simple create a new instance of a JFrame and add your component to it...

public static void go() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            }

            JFrame frame = new JFrame("Testing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new MainProject());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

Fifth

You might want to take a closer look at...

And...

for some more ideas and how you might better manage the CardLayout

You might also like to have a look at How to Use Tabbed Panes for an alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!