Programa donde utilizamos las flechas para mover la imagen (KeyEvent)
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.*;
public class caminando extends JFrame {
Image im1;
int codigo, x=101, y=121;
String dato = "";
int salto=5;
public caminando(){
setSize(500,500);
setTitle("Coche en Movimiento");
setVisible(true);
im1=(Toolkit.getDefaultToolkit().getImage("Viejo.gif"));
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent var){
ProgramacionTeclas(var);
}});
}
public void paint(Graphics a){
//fondo
a.setColor(Color.BLACK);
a.fillRect(0, 0, 500, 500);
//carretera
a.setColor(Color.white);
a.drawLine(100,120,450,120);
a.setColor(Color.magenta);
a.drawLine(100,160,410,160);
a.setColor(Color.cyan);
a.drawLine(410,160,410,380);
a.setColor(Color.blue);
a.drawLine(450,120,450,420);
a.setColor(Color.green);
a.drawLine(410,380,90,380);
a.setColor(Color.orange);
a.drawLine(450,420,90,420);
//meta
a.setFont(new Font("Arial",Font.BOLD,20));
a.setColor(Color.RED);
a.drawString("Meta", 35, 405);
//Inicio
a.setFont(new Font("Arial",Font.BOLD,20));
a.setColor(Color.red);
a.drawString("Inicio", 35, 145);
//coche
a.drawImage(im1,x,y,35,35,this);
}
public void ProgramacionTeclas(KeyEvent z){
codigo=z.getKeyCode();
dato=KeyEvent.getKeyText(codigo);
mueve(dato);
}
public void mueve(String t ){
if(t.equalsIgnoreCase("Derecha")){
if(x<410&&x>90&&y==121){
x=x+salto;
repaint();
}
if(x<410&&x>30&&y==381){
x=x+salto;
repaint();
}
}
if(t.equalsIgnoreCase("Abajo")){
if(x>410&&y<380){
y=y+salto;
repaint();
}
}
if(t.equalsIgnoreCase("Arriba")){
if(x>410&&y>121){
y=y-salto;
repaint();
}
}
if(t.equalsIgnoreCase("Izquierda")){
if(x<412&&x>100&&y==121){
x=x-salto;
repaint();
}
if(x<412&&x>40&&y==381){
x=x-salto;
repaint();
}
}
}
public static void main (String args[]){
caminando termo=new caminando();
termo.setLocation(200,50);
termo.setVisible(true);
}
}
oye amigo para que usaste url? estoy aprendiendo y no me salio el dibujo explicame porfas
ResponderEliminarno funciona :/
ResponderEliminarno compila por:
Imagen im1;
addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent var){
ProgramacionTeclas(var);
}});
//coche
a.drawImage(im1,x,y,35,35,this);
lo otro funciona perfectamente :D