简体   繁体   中英

How to show JPanel over another JPanel and then hide it

So Id like to have 2 JPanels. Up JPanel (introPanel) and down JPanel (mainPanel). Id like to add keyListener to JFrame so when I press any key up panel hides so we can see down panel. How should the code look like to work?

class MainFrame extends JFrame {
    private MainPanel mainPanel = new MainPanel();
    private IntroPanel introPanel = new IntroPanel();

    MainFrame() {
        add(mainPanel);
        add(introPanel);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent ev) {
                introPanel.setVisible(false);
            }
        });
        pack();
        setVisible(true);
    }

}

This code doesn't hide introPanel. What's wrong?

You can only place one component in the BorderLayout.CENTER position so the introPanel displaces mainPanel when it is added. You have to add the mainPanel if you wish that to appear:

add(mainPanel);
revalidate();
repaint();

Consider using a CardLayout . It supports the notion of "stacking" components in this manner.

Also consider using Key Bindings for Swing based applications. Unlike KeyListeners , Key Bindings do not require focus to interact with KeyEvents .

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