0

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?

4

1 回答 1

3

您只能将一个组件放置在该BorderLayout.CENTER位置,以便在添加时发生introPanel位移mainPanelmainPanel如果您希望它出现,您必须添加:

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

考虑使用CardLayout。它以这种方式支持“堆叠”组件的概念。

还可以考虑为基于 Swing 的应用程序使用键绑定。与不同KeyListeners的是,Key Bindings 不需要焦点来与之交互KeyEvents

于 2013-02-19T20:19:40.513 回答