展开全部
看看例子吧。按上下左右图片移动
package demo;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
class Demo extends JFrame {
private MovePanel mp;
public Demo() {
mp = new MovePanel();
add(mp);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
mp.requestFocus();
}
public static void main(String[] args) {
new Demo();
}
}
@SuppressWarnings("serial")
class MovePanel extends JPanel {
private final int MOVE_SPACE = 10;;
private BufferedImage img;
private int x;
private int y;
public MovePanel() {
this.requestFocus();
try
{
img = ImageIO.read(new File("2.jpg"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
addKeyListener(new MoveListener());
x = 0;
y = 0;
}
@Override
public void paint(Graphics g) {
super.paint(g);
System.out.println(x + " " + y);
g.drawImage(img, x, y, null);
}
private class MoveListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
y -= MOVE_SPACE;
break;
case KeyEvent.VK_DOWN:
y += MOVE_SPACE;
break;
case KeyEvent.VK_LEFT:
x -= MOVE_SPACE;
break;
case KeyEvent.VK_RIGHT:
x += MOVE_SPACE;
break;
}
MovePanel.this.repaint();
System.out.println("SDf");
}
}
}
package demo;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
class Demo extends JFrame {
private MovePanel mp;
public Demo() {
mp = new MovePanel();
add(mp);
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
mp.requestFocus();
}
public static void main(String[] args) {
new Demo();
}
}
@SuppressWarnings("serial")
class MovePanel extends JPanel {
private final int MOVE_SPACE = 10;;
private BufferedImage img;
private int x;
private int y;
public MovePanel() {
this.requestFocus();
try
{
img = ImageIO.read(new File("2.jpg"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
addKeyListener(new MoveListener());
x = 0;
y = 0;
}
@Override
public void paint(Graphics g) {
super.paint(g);
System.out.println(x + " " + y);
g.drawImage(img, x, y, null);
}
private class MoveListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
y -= MOVE_SPACE;
break;
case KeyEvent.VK_DOWN:
y += MOVE_SPACE;
break;
case KeyEvent.VK_LEFT:
x -= MOVE_SPACE;
break;
case KeyEvent.VK_RIGHT:
x += MOVE_SPACE;
break;
}
MovePanel.this.repaint();
System.out.println("SDf");
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询