为什么此KeyEvent无法正常工作? [英] Why wont this KeyEvent work?

查看:169
本文介绍了为什么此KeyEvent无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java制作一些东西,当按下F1键时会弹出一个JDialog窗口.我当前的代码:

I am making something in java that when the F1 key is hit a JDialog window to apear.My current code:

public class Keyboard implements KeyListener {

    private boolean[] keys = new boolean[120];

    public boolean up, down, left, right, assets;

    public void tick() {

        assets = keys[KeyEvent.VK_F1];
    }

    public void keyPressed(KeyEvent e) {

        keys[e.getKeyCode()] = true;
    }

    public void keyReleased(KeyEvent e) {

        keys[e.getKeyCode()] = false;
    }

    public void keyTyped(KeyEvent e) {


    }

}

在我的主类中的tick()方法下:

And in my main class under the tick() method:

keyboard.tick();
if(keyboard.assets) ac.run();

keyboard变量指的是键盘类,而ac变量指的是此类:

The keyboard variable refers to the keyboard class while the ac variable refers to this class:

public class AssetsChooser extends JDialog {

    JFileChooser fc = new JFileChooser();

    public void run() {

        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        add(fc);

        System.out.println("It works.");
    }
}

当我运行游戏并按F1时,没有JDialog窗口出现,控制台也没有显示该方法.

When I run my game and hit F1 no JDialog window appears nor does the Console display the method.

推荐答案

Swing中经常存在与KeyListener相关的焦点问题.如KeyListener教程中所述:

There are often focus issues related with KeyListener in Swing. As noted in the KeyListener tutorial:

要定义对特定键的特殊反应,请使用键绑定而不是键侦听器.有关更多信息,请参见

一个例子(只需按 F1 ):

import java.awt.event.*;
import javax.swing.*;

public class TestF1KeyBind {

    public TestF1KeyBind() {
        final JFrame frame = new JFrame("Frame");
        JPanel panel = new JPanel();

        InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "openDialog");
        ActionMap am = panel.getActionMap();
        am.put("openDialog", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(frame, true);
                dialog.setSize(300, 300);
                dialog.setTitle("Dialog");
                dialog.setLocationByPlatform(true);
                dialog.setVisible(true);
            }
        });

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestF1KeyBind();
            }
        });
    }
}

这篇关于为什么此KeyEvent无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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