How do I use Key Listener to close a panel?
I am trying to get my load frame to close when the enter key is pushed. Can anyone help. I wanted to put an if statement in my constructor this if statement does get accessed however it does not work. I read something about repainting and validating however not sure if I implementing this correctly. I just want the load panel to close and then display the game panel. A more direct question would be why is the if (enter == true) not being accessed when I push enter. The enter variable does get updated on key press but the if statement does not activate. Why?
public class GameFrame implements KeyListener {
boolean enter = false;
boolean focus = true;
public GameFrame() {
Game game = new Game();//constructor of game instane
game.setFocusable(focus);
JFrame frame = new JFrame(); // constructor of JF instance
frame.setBounds(0, 0, Game.HEIGHT, Game.WIDTH);
frame.setTitle(Game.TITLE);
LoadingPanel load = new LoadingPanel();
load.setSize(Game.WIDTH - 40, Game.HEIGHT - 40);
load.setLocation(20, 20);
load.setVisible(true);
load.addKeyListener(this);
load.setFocusable(focus);
frame.add(load);
frame.add(game);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
game.setVisible(true);
frame.setVisible(true);
if (enter == true){
System.out.println("xx");//test for access
frame.remove(load);
frame.validate();
frame.repaint();
}
game.start();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
this.enter = true;
this.focus = true;//setting to true just in case
System.out.println("GameFrame pressed");
System.out.println("enter is " + this.enter);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
Thanks in advance for any help.
UPDATE: The following code used Keybinding and it works perfect.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class GameFrame {
LoadingPanel load;
public GameFrame() {
Game game = new Game();//constructor of game instance
JFrame frame = new JFrame(); // constructor of JF instance
frame.setBounds(0, 0, Game.HEIGHT, Game.WIDTH);
frame.setTitle(Game.TITLE);
load = new LoadingPanel();
load.setSize(Game.WIDTH - 40, Game.HEIGHT - 40);
load.setLocation(20, 20);
load.setVisible(true);
frame.add(load);
frame.add(game);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
game.setVisible(true);
frame.setVisible(true);
game.start();
InputMap im = load.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = load.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
am.put("Enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
frame.remove(load);
}
});
}
}