现在的位置: 首页 > 综合 > 正文

给菜单添加快捷键

2012年09月29日 ⁄ 综合 ⁄ 共 1935字 ⁄ 字号 评论关闭

Menu Shortcuts
菜单快捷键
The ability to specify menu shortcuts is one of the features in JDK 1.1 -- where menu choices can be selected via the keyboard instead of with the mouse.
在jdk1.1中提供了菜单快捷键的实现.快捷键---就是利用键盘取代鼠标选择菜单项.

For example:
一个例子:
//导入需要的包
import java.awt.*;
import java.awt.event.*;
//Menu类,实现ActionListener接口
public class menu implements ActionListener {
  public void actionPerformed(ActionEvent e)
  {
    String lab = ((MenuItem)e.getSource()).getLabel();
    System.out.println("label = " + lab);
    if(lab.equals("Exit"))
    {
      System.exit(0);
    }
  }

  public static void main(String args[])
  {
    Frame f = new Frame("testing");
        
    Menu m = new Menu("File");
        
    menu acl = new menu();
        
    MenuItem mi1 = new MenuItem("Open");
    mi1.addActionListener(acl);
    m.add(mi1);
        
    MenuItem mi2 = new MenuItem("Save");
    mi2.addActionListener(acl);
    m.add(mi2);
    //创建快捷方式,这里将会依赖于平台,使用快捷键,在Windows下,将会是C+E    
    MenuShortcut ms3 = new MenuShortcut(KeyEvent.VK_E);
    MenuItem mi3 = new MenuItem("Exit", ms3);
    mi3.addActionListener(acl);
    m.add(mi3);
        
    MenuBar mb = new MenuBar();
    mb.add(m);
        
    f.setMenuBar(mb);
    f.setSize(200, 200);
    f.setVisible(true);
  }

}

The example sets up a frame, which is a top-level application window. The frame contains a menu bar, and the menu bar contains a single pull-down menu named "File." The menu offers choices for Open, Save, and Exit, with Exit having a keyboard shortcut set up for it that specifies the virtual key code "E."
这个例子构建了一个Frame作为顶层窗口,窗口有一个菜单栏,菜单栏里只有File一项菜单,File菜单提供了Open,Save,Exit三项,Exit项绑定了一个快捷键E.

How the shortcut gets invoked varies, depending on the platform in question. For example, with Windows you use Ctrl-E so that when a user types Ctrl-E within the window containing the menu bar, the Exit command is invoked.
快捷键通过什么方式执行是依赖于平台的,比如,在Windows下,对应的是Ctrl-E,当你按下Ctrl-E时,Exit命令就会执行.

One last thing: this example doesn't actually(事实上,居然) have a command structure(构建,构造) set up for it, but instead invokes actionPerformed to demonstrate(证明) that the command processing structure is in place.
最后一件事:这个例子实际上并没有构建一个命令处理结构,但是只是调用actionPerformed证明命令处理结构已经正确执行了。

抱歉!评论已关闭.