package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestKey {
public static void main(String[] args) {
new KeyFrame().launchFrame();
}
}
class KeyFrame extends Frame {
public void launchFrame() {
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setBounds(500, 200, 300, 300);
frame.setLayout(new BorderLayout(10, 10));
JButton b1 = new JButton("Up");
frame.add(b1, BorderLayout.NORTH);
b1.addKeyListener(new MyKeyMonitor());
JButton b2 = new JButton("Right");
frame.add(b2, BorderLayout.EAST);
b2.addKeyListener(new MyKeyMonitor());
JButton b3 = new JButton("Down");
frame.add(b3, BorderLayout.SOUTH);
b3.addKeyListener(new MyKeyMonitor());
JButton b4 = new JButton("Left");
frame.add(b4, BorderLayout.WEST);
b4.addKeyListener(new MyKeyMonitor());
frame.add(new JButton("Centre"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口
frame.setVisible(true);
}
class MyKeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_UP) {
System.out.println("上");
}
if(keyCode == KeyEvent.VK_DOWN) {
System.out.println("下");
}
if(keyCode == KeyEvent.VK_LEFT) {
System.out.println("左");
}
if(keyCode == KeyEvent.VK_RIGHT) {
System.out.println("右");
}
}
}
}