为什么这个KeyEvent不起作用?

时间:2014-03-23 01:48:54

标签: java swing keylistener jdialog keyevent

我正在java中制作一些东西,当F1键被击中JDialog窗口到apear时。我的当前代码:

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()方法:

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

键盘变量是指键盘类,而ac变量是指这个类:

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窗口,控制台也没有显示该方法。

1 个答案:

答案 0 :(得分:2)

Swing中经常出现与KeyListener相关的焦点问题。正如KeyListener教程中所述:

  

“要定义对特定键的特殊反应,请使用键绑定而不是键侦听器。有关详细信息,请参阅How to Use Key Bindings。”

一个例子(只需点击 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();
            }
        });
    }
}