import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.BoxLayout;
import java.awt.Container;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class KeyDemo1 extends JFrame implements ActionListener {
Marker marker;
JButton button;
public static void main(String arg[]) {
new KeyDemo1();
}
public KeyDemo1() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
KeyStroke ks;
Container pane = getContentPane();
BoxLayout boxlayout = new BoxLayout(pane,BoxLayout.Y_AXIS);
pane.setLayout(boxlayout);
button = new JButton("Focus");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(button);
marker = new Marker(200,200);
pane.add(marker);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0);//获取KeyStroke对象
button.registerKeyboardAction(this,"PageUp",ks,//将其注册监听
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,0);
button.registerKeyboardAction(this,"PageDown",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0);
button.registerKeyboardAction(this,"Down",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_UP,0);
button.registerKeyboardAction(this,"Up",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0);
button.registerKeyboardAction(this,"Left",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0);
button.registerKeyboardAction(this,"Right",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_HOME,0);
button.registerKeyboardAction(this,"Home",ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
pack();
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Home"))
marker.setMiddle();
else if(command.equals("PageUp"))
marker.setTop();
else if(command.equals("PageDown"))
marker.setBottom();
else if(command.equals("Up"))
marker.moveUp();
else if(command.equals("Down"))
marker.moveDown();
else if(command.equals("Left"))
marker.moveLeft();
else if(command.equals("Right"))
marker.moveRight();
System.out.println(command);
}
}