Media/fn keys in java

2019-05-17 20:06发布

问题:

I am currently developing a media application in java using the gstreamer bindings for java. All is going well except for one small issue regarding the keyboard, specifically the media keys (e.g. play/pause, back, next).

I have Actions that work fine as buttons/menu items for these functions, and was hoping to allow the use of the keys that are on some keyboards (often on laptops). However, I could not find andthing in java.awt.event.KeyEvent to represent these keys. I tried running the snippet of code below, and it worked fine for most keys, including f1-12, but did not respond to 'fn' nor to the media keys while 'fn' was held.

Does anyone know how to get these keys working?

Code:

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

public class Key extends JFrame{

    public Key(){

        JTextField f = new JTextField(50);
        f.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){
                System.out.printf("%s : %d \n", e.getKeyChar(), e.getKeyCode());
            }
        });
        setContentPane(f);
        pack();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);

    }

    public static void main(String[] args){
        new Key();  
    }

}

回答1:

If the e.getKeyChar() and e.getKeyCode() keys don't return anything when you press those keys, I'm not aware of any other way to get those events via the standard Java library, other than using JNI to get the codes at a lower level.

You seem to be on the right track, trying to get the key codes when a key is pressed, which is how you would discover key codes when you don't know what the proper constant is in Java.

Other than that, this question seems to offer some possibilities (though I'm not sure if this only works with Microsoft IntelliType devices, or if it will work cross-platform). When I use a Microsoft IntelliType keyboard on my Mac, for example, the media keys seem to work just fine.