Using CardLayout for multiple JPanels and nothing displays

后端 未结 1 1748
感动是毒
感动是毒 2021-01-27 09:25

I\'m making a simple (and bogus) computer power consumption calculator. I\'m using a card layout to put multiple panels in but when I run it, there\'s just a small window not di

相关标签:
1条回答
  • 2021-01-27 10:08

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

    • Creating a GUI With JFC/Swing
    • How to Use CardLayout

    And...

    • Why is my JLabel not showing up
    • Listener Placement Adhering to the Traditional (non-mediator) MVC Pattern

    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

    0 讨论(0)
提交回复
热议问题