KeyListener will not work with dispose();

2019-08-29 08:29发布

I am trying to close a window when a user presses the escape key and open a new window. For some reason, when I add dispose(); to the key listener, it doesnt work.

Any idea on how to fix this?

Thanks in advance!

Here is the code:

public class About extends JPanel implements KeyListener{

Font menu = new Font("SansSerif", Font.BOLD, 12);
Font title = new Font("SansSerif", Font.BOLD, 14);
Font version = new Font("Monospaced", Font.ITALIC, 12);
boolean falling = false;

public About() {

    JFrame frame = new JFrame("Tiny Runner");
    frame.add(this);
    frame.setBounds(0, 0, 800, 600);
    frame.addKeyListener(this);
    frame.setFocusable(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);
    }
public void keyPressed(KeyEvent keyEvent) {
    if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
            new MainMenu();
            dispose();
    }
}

2条回答
【Aperson】
2楼-- · 2019-08-29 09:07

You should NOT be using a KeyListener for this.

Instead you should be using Key Bindings and you should add the binding to the root pane. See Key Bindings for more info. Since the bindings are added to the root pane this should be done when you create your frame so you will have access to the frame.

查看更多
相关推荐>>
3楼-- · 2019-08-29 09:08

Why would it know what to do when you call dispose? What should be disposed?

You should make the frame a class variable, and then call dispose like frame.dispose();

查看更多
登录 后发表回答