最近看到有人问怎么模拟钢琴操作
想了想怎么实现 顺便看了下键盘事件
可以用两种方式
1、
public class KeystrokeTest extends JApplet {
private JButton button = new JButton("button");
public void init() {
Container contentPane = getContentPane();
JPanel panel = new JPanel();
JCheckBox checkbox = new JCheckBox("checkbox");
JButton southButton = new JButton("south button");
Listener listener = new Listener();
panel.setBorder(BorderFactory
.createTitledBorder(("Ancestor of button and checkbox")));
checkbox.registerKeyboardAction(listener, KeyStroke.getKeyStroke (
KeyEvent.VK_F, 0, false), JComponent.WHEN_FOCUSED);
panel.registerKeyboardAction(listener, KeyStroke.getKeyStroke (
KeyEvent.VK_A, InputEvent.ALT_MASK, false),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
southButton.registerKeyboardAction(listener, KeyStroke.getKeyStroke(
KeyEvent.VK_W, 0, true), JComponent.WHEN_IN_FOCUSED_WINDOW);
panel.add(button);
panel.add(checkbox);
contentPane.add(panel, "Center");
contentPane.add(southButton, "South");
}
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
String cname = src.getClass().getName();
if (src instanceof JCheckBox) {
System.out.print("'f' key PRESSED when checkbox");
System.out.println(" had focus");
} else if (src instanceof JPanel) {
System.out.print("'ALT-a' key PRESSED when ancestor");
System.out.println(" of titled panel had focus");
} else if (src instanceof JButton) {
System.out.print("'w' key RELEASED when any");
System.out.println(" component in window had focus");
}
System.out.println("Source: " + cname);
System.out.println();
}
}