上面我错了点,img是jlabel,不是图像对象。。。
给你一个完整的。。
package com.magic;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Magic extends JFrame{
/** ********************* init Window ***********************/
/**
* default id
*/
private static final long serialVersionUID = 5404139822298151466L;
private Toolkit t = Toolkit.getDefaultToolkit();
/**
* default construction
*/
public Magic(){
initForm();
}
/**
* init JFrame
*
*/
private void initForm() {
final JLabel img = initMainImagePanel();
this.add(img);
this.setTitle("Test");
this.setSize(600, 500);
this.setLocation(
(int) (t.getScreenSize().getWidth() - this.getWidth()) / 2,
(int) (t.getScreenSize().getHeight() - this.getHeight()) / 2);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent arg0) {
int imgX = (int) img.getLocation().getX();
int imgY = (int) img.getLocation().getY();
switch (arg0.getKeyCode()) {
case KeyEvent.VK_UP:
img.setLocation((int) (imgX),(int) (imgY-5));
break;
case KeyEvent.VK_DOWN:
img.setLocation((int) (imgX),(int) (imgY+5));
break;
case KeyEvent.VK_LEFT:
img.setLocation((int) (imgX-5),(int) (imgY));
break;
case KeyEvent.VK_RIGHT:
img.setLocation((int) (imgX+5),(int) (imgY));
break;
default:
break;
}
}
});
}
/**
* init MainImagePanel
* @return
*/
public JLabel initMainImagePanel(){
Image img = t.getImage("com/magic/panda.gif");
JLabel l =new JLabel(initMainImage(img));
return l;
}
/**
* init Image
* @param imgPath
* @return
*/
public ImageIcon initMainImage(Image imgPath){
ImageIcon img = new ImageIcon(imgPath);
return img;
}
/** ********************* init Window ***********************/
/**
* @param args
*/
public static void main(String[] args) {
new Magic();
}
}