日期:2014-05-20  浏览次数:20692 次

如何对控件设置按键监听
想对一个菜单项设置为监听键盘的ctrl+s,如何做到呢?

求前辈指点,根据API里,就知道怎么用SHIFT而已..........



------解决方案--------------------
主要是这句:
setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
示例如下:
import java.awt.event.*;
import javax.swing.*;


public class MenuTest
{
public static void main(String[] args)
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle( "MenuTest ");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

JMenu fileMenu = new JMenu( "File ");

saveAction = new TestAction( "Save ");
JMenuItem saveItem = fileMenu.add(saveAction);
saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

menuBar.add(fileMenu);
}

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;

private Action saveAction;
}

class TestAction extends AbstractAction
{
public TestAction(String name) { super(name); }

public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) + " selected. ");
}
}