日期:2014-05-20 浏览次数:20680 次
import javax.swing.*;
import java.awt.event.*;
public class TestFrame {
public static void main(String[] args) {
MyTestFrame myframe=new MyTestFrame();
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
class MyTestFrame extends JFrame {
MyTestFrame(){
JButton button=new JButton("test");
MyTestPanel mytestpanel=new MyTestPanel();
mytestpanel.add(button);
add(mytestpanel);
addKeyListener(mytestpanel);
}
}
class MyTestPanel extends JPanel implements KeyListener{
MyTestPanel(){
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_DOWN){
System.out.println("向下");
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
System.out.println("向右");
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT){
System.out.println("向左");
}
else if(e.getKeyCode()==KeyEvent.VK_UP){
System.out.println("向上");
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
MyTestFrame() {
JButton button = new JButton("test");
MyTestPanel mytestpanel = new MyTestPanel();
mytestpanel.add(button);
add(mytestpanel);
addKeyListener(mytestpanel);
///
button.addKeyListener(mytestpanel);
}