Domanda

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


    }

}

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

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

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.");
    }
}

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

È stato utile?

Soluzione

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

"To define special reactions to particular keys, use key bindings instead of a key listener. For further information, see How to Use Key Bindings."

An example (just hit 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();
            }
        });
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top