Reputation: 1
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?
Upvotes: 0
Views: 2379
Reputation: 159754
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
.
Upvotes: 3