像这样跟随鼠标移动图像一样,让图像跟随方向键移动import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class mouse extends Applet implements MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 3020610036335839246L;
int x=5,y=5;
public void init()
{
setBackground(Color.cyan);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,8,8);
g.drawOval(x,y,8,8);
}
public void mouseMoved(MouseEvent e)
{
x=(int)e.getX();
y=(int)e.getY();
repaint();
}
public void mouseDragged(MouseEvent e){}
}
import java.awt.*;
import java.awt.event.*;
public class mouse extends Applet implements MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 3020610036335839246L;
int x=5,y=5;
public void init()
{
setBackground(Color.cyan);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,8,8);
g.drawOval(x,y,8,8);
}
public void mouseMoved(MouseEvent e)
{
x=(int)e.getX();
y=(int)e.getY();
repaint();
}
public void mouseDragged(MouseEvent e){}
}
{
private static final long serialVersionUID = 3020610036335839246L;
int x=5,y=5;
public void init()
{
setBackground(Color.cyan);
addKeyListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,8,8);
g.drawOval(x,y,8,8);
} public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() != KeyEvent.VK_UP
|| e.getKeyCode() != KeyEvent.VK_DOWN
|| e.getKeyCode() != KeyEvent.VK_LEFT
|| e.getKeyCode() != KeyEvent.VK_RIGHT){
return;
} if(e.getKeyCode() == KeyEvent.VK_UP){
y = y > 0 ? y - 1 : 0;
} else if(e.getKeyCode() == KeyEvent.VK_DOWN){
y = y < this.getHeight() ? y + 1 : this.getHeight();
} else if(e.getKeyCode() == KeyEvent.VK_LEFT){
x = x > 0 ? x - 1 : 0;
} else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
x = x < this.getWidth() ? x + 1 : this.getWidth();
}
repaint();
}
public void keyTyped(KeyEvent e) {
}
}