要求:
界面如图,应用程序可能通过键盘上的方向键(上,下,左,
右) 控制按键分别向对应的方向移动。
代码:
public class test {
public static void main(String args[]){
Win win=new Win();
win.setTitle("KeyEvent事件");
win.setBounds(20,20,400,350);
}
}
import java.awt.*;
import javax.swing.*;
public class Win extends JFrame{
JButton b;
Police police;
Win(){
setLayout(null);
police=new Police();
b=new JButton("请按方向键移动");
police.setJButton(b);
b.addKeyListener(police);
b.addFocusListener(police);
b.requestFocusInWindow();
b.setBounds(120,100,130,40);
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.event.*;
import javax.swing.*;
public class Police implements KeyListener,FocusListener {
JButton b;
public void setJButton(JButton b){
this.b=b;
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==37){
b.setLocation(b.getX()-100,b.getY());//左
}
if(e.getKeyCode()==39){
b.setLocation(b.getX()+130,b.getY());//右
}
if(e.getKeyCode()==40){
b.setLocation(b.getX(),b.getY()+80);//上
}
if(e.getKeyCode()==38){
b.setLocation(b.getX(),b.getY()-100);//下
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e){}
}