Search code examples
javalinuxswingawtawtrobot

KeyEvent.VK_CONTEXT_MENU doesn't work when sent by Robot on Linux


I am trying to test a Swing component that shows a menu when the context menu key is pressed. I simply get a focus in the component and send a press & release events by the awt Robot. It works on Windows but not on Linux. Here is an example Java code that shows the key event integer code. When this is run, the key event is set to 0. However when you press the key physically, it appears correctly as 525.

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

public class ContextMenuKeyTest {
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel panel = new JPanel();
                JLabel label = new JLabel("Type something");
                JTextField comp = new JTextField("Hello World!");
                comp.setPreferredSize(new Dimension(300,100));
                panel.add(label);
                panel.add(comp);
                comp.addKeyListener(new KeyListener() {
                    @Override
                    public void keyTyped(KeyEvent e) {}
                    @Override
                    public void keyPressed(KeyEvent e) {
                        label.setText("Pressed: " + e.getKeyCode());
                    }
                    @Override
                    public void keyReleased(KeyEvent e) {}
                });

                frame.add(panel);
                frame.pack();
                frame.setVisible(true);
                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_C);
                    robot.keyRelease(KeyEvent.VK_C);
                    robot.keyPress(KeyEvent.VK_CONTEXT_MENU);
                    robot.keyRelease(KeyEvent.VK_CONTEXT_MENU);
                } catch (AWTException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

The windows key also doesn't work properly when pressed by the robot and works just fine when pressed physically. Other keys work just fine.

Tested on Ubuntu with IceWM and on Debian with Xfce with Java 8.


Solution

  • I am not sure why the key doesn't work when using Robot. As a workaround I am using a xdotool that sends the key by calling:

    xdotool key Menu