简体   繁体   中英

Java Swing: How can I change a button's text when the Alt key is held?

I have a Swing gui I'm working on. I have a "Save" button, and I want it to delete an entry instead of saving if it's clicked when the Alt key is held down. Checking whether alt is held when the button is clicked is no problem. That's not what this question is about.

I want the text of the "Save" button to change to "Delete" when Alt is pressed, and back to "Save" when Alt is released.

I've tried adding a KeyListener to my JPanel but it doesn't seem to activate, possibly because the panel itself doesn't have the focus because focus is on one of its children.

I've tried a key binding via JComponent InputMap and ActionMap, but I can't figure out a KeyStroke which corresponds to just the Alt key. My unsuccessful best guess at how that would look:

myPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("alt"), "altKey");
myPanel.getActionMap().put("altKey", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent event) {
        log.info("alt has been pressed.");
        saveButton.setText(event.getModifiers() == KeyEvent.VK_ALT ? "Delete" : "Save");
    }
});

How can I get code to execute when the Alt key itself is pressed/released, regardless of where the focus is in the window?

To handle key events regardless of which element currently has the focus, use a KeyEventDispatcher attached to the current KeyboardFocusManager, eg:

KeyboardFocusManager.getCurrentKeyboardFocusManager()
    .addKeyEventDispatcher((KeyEvent event) -> {
        if (event.isAltDown()) {
            saveButton.setText("Delete");
        } else {
            saveButton.setText("Save");
        }
        return false; // `false` allows further handling by other code
    });

Thanks to @AliasCartellano

Note: there does seem to be a small, unpredictable delay between when you press the Alt key and when the event fires. Maybe because it's a modifier key? I'm unclear on whether that delay can be eliminated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM