Swing 단축키(KeyStroke) 등록하기
프로그래밍/java 2021. 12. 13. 21:00반응형
ESC 입력시 창 닫기
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);
}
}
반응형