Dim
Dim

Reputation: 4807

Java Swing get input

How can I change this code to accept any key (not only F5) and print the key?

component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "F5 Pressed");
component.getRootPane().getActionMap().put("F5 Pressed", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Code here
    }
});

Upvotes: 0

Views: 112

Answers (2)

Elist
Elist

Reputation: 5533

Use KeyboardFocusManager to register a KeyEventDispatcher:

KeboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {       
    @Override
    public boolean dispatchKeyEvent(KeyEvent ke) {
        if (yourComponent.hasFocus && ke.getID == KeyEvent.KEY_TYPED) {
            // Your code here
            // Use ke.getKeyChar() to detect which key was pressed.
        }
    }
}

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

how can I ("cahnhe") this code to accept any key (not only F5) and print the key?

Upvotes: 2

Related Questions