提问者:小点点

为什么这个KeyEvent不能工作?


我在java,当F1键被击中JDialog窗口apear.My当前代码的东西:

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) {


    }

}

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

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个答案

匿名用户

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

"要定义对特定键的特殊反应,请使用键绑定而不是键侦听器。有关详细信息,请参阅如何使用键绑定。"

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