Java6学习笔记44——JAVA中的热键实例2

此例中组件的焦点和窗体的焦点都响应热键。

import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JComponent;
import javax.swing.BoxLayout;
import java.awt.Container;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

public class KeyDemo2 extends JFrame implements KeyEventDispatcher {
KeyboardFocusManager manager;
Marker marker;
JTextField textField;
public static void main(String arg[]) {
new KeyDemo2();
}
public KeyDemo2() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);

manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();//获取KeyboardFocusManager对象
manager.addKeyEventDispatcher(this);//增加一个调度链
}
private void buildFrame() {
Container pane = getContentPane();
BoxLayout boxlayout = new BoxLayout(pane,BoxLayout.Y_AXIS);
pane.setLayout(boxlayout);

textField = new JTextField(10);
textField.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(textField);

marker = new Marker(200,200);
pane.add(marker);

pack();
}
public boolean dispatchKeyEvent(KeyEvent e) {//实现 KeyEventDispatcher接口,完成响应程序
int code = e.getKeyCode();
switch(code) {
case KeyEvent.VK_HOME:
marker.setMiddle();
break;
case KeyEvent.VK_PAGE_UP:
marker.setTop();
break;
case KeyEvent.VK_PAGE_DOWN:
marker.setBottom();
break;
case KeyEvent.VK_UP:
marker.moveUp();
break;
case KeyEvent.VK_DOWN:
marker.moveDown();
break;
case KeyEvent.VK_LEFT:
marker.moveLeft();
break;
case KeyEvent.VK_RIGHT:
marker.moveRight();
break;
}
return(false);//如果指派了 KeyEvent,则返回 true ;否则,返回 false
}
}

你可能感兴趣的:(java,swing,UP)