KeyListener不能与dispose()一起使用; [英] KeyListener will not work with dispose();

查看:120
本文介绍了KeyListener不能与dispose()一起使用;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下退出键并打开一个新窗口时,我正在尝试关闭一个窗口.由于某种原因,当我添加dispose()时;到关键侦听器,它不起作用.

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?

提前谢谢!

这是代码:

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();
    }
}

推荐答案

您不应为此使用KeyListener.

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.

这篇关于KeyListener不能与dispose()一起使用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆