import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Animation extends JFrame implements Runnable,ActionListener,KeyListener{
private Container cont;
private JButton btnUp;
private JButton btnDown;
private ImageIcon imgPlane;
private ImageIcon imgBullet;
private int planeX;
private int planeY;
private int bulletX;
private int bulletY;
private int planeSpeed;
private int bulletSpeed;
private int planeChangeSpeed;
private Thread thread;
public Animation(){
addKeyListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
GameStartInit();
}
public void GameStartInit(){
cont =this.getContentPane();
this.setBounds(0,0,400,300);
cont.setLayout(null);
imgPlane = new ImageIcon("plane.gif");
imgBullet = new ImageIcon("bullet.gif");
planeX = 0;
planeY = 150;
bulletX = 400;
bulletY = 150;
planeSpeed = 8;
bulletSpeed = 8;
planeChangeSpeed = 6;
btnUp = new JButton("up");
btnDown = new JButton("down");
btnUp.setBounds(0, 240, 80, 30);
btnDown.setBounds(90, 240, 80, 30);
btnUp.addActionListener(this);
btnDown.addActionListener(this);
cont.add(btnUp);
cont.add(btnDown);
thread = new Thread(this);
thread.start();
this.setVisible(true);
}
public void paint(Graphics grp){
super.paint(grp);
imgPlane.paintIcon(this, grp, planeX, planeY);
imgBullet.paintIcon(this, grp, bulletX, bulletY);
}
public void run(){
while((bulletX > 0) &&(planeX < 400)){
repaint();
planeX = planeX + planeSpeed;
bulletX = bulletX - bulletSpeed;
try{
Thread.sleep(200);
}catch(Exception e){}
}
thread = null;
}
public void actionPerformed(ActionEvent aEvt){
JButton ob=(JButton)aEvt.getSource();
if(ob == btnUp){
planeY-=planeChangeSpeed;
}
if(ob == btnDown){
planeY += planeChangeSpeed;
}
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_UP:
planeY = planeY - 5;
break;
case KeyEvent.VK_DOWN:
planeY = planeY + 5;
break;
case KeyEvent.VK_LEFT:
planeX = planeX - 5;
break;
case KeyEvent.VK_RIGHT:
planeX = planeX + 5;
break;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public static void main(String args[]){
new Animation();
}
}
那怎么改啊?不是窗口监听键盘事件吗?改好了我加分
追答你想要完成什么功能?? 想要利用JFrame监听那个组件?
追问按上下左右方向键可以控制图片的移动