Registering a Java Swing KeyStroke

Close window when ESC is pressed


package test.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;

public class MainTest {
    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
        mainUI.setVisible(true);
    }
}

class MainUI extends JFrame {
    MainUI() {
        setPreferredSize(new Dimension(400, 300));
        setLayout(new FlowLayout());
        JButton button = new JButton("TEST");
        button.setPreferredSize(new Dimension(100, 100));
        add(button);
        pack();

        KeyStroke escStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        String actionMapKey = getClass().getName() + ":WINDOW_CLOSING";
        Action closingAction = new AbstractAction() {
            public void actionPerformed(ActionEvent event) {
                MainUI.this.dispatchEvent(new WindowEvent(MainUI.this, WindowEvent.WINDOW_CLOSING));
            }
        };

        installKeyStroke(this, escStroke, actionMapKey, closingAction);
    }

    public void installKeyStroke(final RootPaneContainer container, final KeyStroke stroke, final String actionMapKey, final Action action) {
        JRootPane rootPane = container.getRootPane();
        rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, actionMapKey);
        rootPane.getActionMap().put(actionMapKey, action);
    }
}

Generate a key with the class name to be registered (to prevent duplication)

String actionMapKey = getClass().getName() + ":WINDOW_CLOSING";

 

No comments:

Lognote - My toy project

In a project, the code work is limited When I say, "I think it will work if I change it like this," I get, "If it doesn't...