在 switch 语句中使用 ctrl-z 撤消的非弃用方法

Non-deprecated method for using ctrl-z to undo in a switch statement

我需要在 switch 中使用 ctrl-z 使我的撤消案例生效,但我尝试过的所有方法都已弃用或不起作用

switch (event.getActionCommand()) {
       case "Undo":
            try {
              // undo method
            } catch(Exception e){
              // exception msg
            }
            break;

            case "Redo":
              try{
                // redo method
            } catch(Exception e){
               // exception msg
            }
            break;
 }

目前,这些可以通过 jmenu 项访问,但我希望通过控件 z 也可以使用 under 方法,撤消和重做的内容在 jframe 中。

不要误会我的意思,它们是否通过对应的 jmenu 功能正常运行,我只是无法通过按键 (ctrl+z) 让它们正常工作

I just cannot get them to work through key presses (ctrl+z)

您需要在菜单项中添加 "accelerator"。

undoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));

阅读 Enabling Keyboard Operation 上的 Swing 教程部分了解更多信息。