Bueno para no complicar las cosas te dejo aquí lo que es los códigos completo de 3 archivos (movimientos con teclas):
el principal:
movi_teclas:
Código:
package unprograma;
import javax.swing.*;
public class movi_teclas extends JFrame {
public movi_teclas(){
super("Prueba ventana");
add(new dibujar());
setSize(800,600);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
public static void main (String args[]){
new movi_teclas();
}
}
casa:
Código:
package unprograma;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class casa {
private String casa = "logo.png";
private int dx;
private int dy;
private int x;
private int y;
private Image imagen;
public casa(){
x=40;
y=60;
ImageIcon img = new ImageIcon(this.getClass().getResource(casa));
imagen = img.getImage();
}
public void mover(){
x+=dx;
y+=dy;
}
public int tenerX(){
return x;
}
public int tenerY(){
return y;
}
public Image tenerImagen(){
return imagen;
}
public void KeyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
dx = -1;
}
if(key == KeyEvent.VK_RIGHT){
dx = 1;
}
if(key == KeyEvent.VK_UP){
dy = -1;
}
if(key == KeyEvent.VK_DOWN){
dy = 1;
}
}
public void KeyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
dx = 0;
}
if(key == KeyEvent.VK_RIGHT){
dx = 0;
}
if(key == KeyEvent.VK_UP){
dy = 0;
}
if(key == KeyEvent.VK_DOWN){
dy = 0;
}
}
}
Y por último el archivo donde me da el error del graphics:
dibujar:
Código:
package unprograma;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class dibujar extends JPanel implements ActionListener {
private casa casa;
private Timer timer;
public dibujar(){
setBackground(Color.black);
setFocusable(true);
addKeyListener(new teclado());
casa = new casa();
timer =new Timer(5, this);
timer.start();
}
private void paint(Graphics grafica){
super.paint(grafica);
Graphics2D g2 = (Graphics2D) grafica;
g2.drawImage(casa.tenerImagen(), casa.tenerX(), casa.tenerY(), null);
}
public void actionPerformed(ActionEvent e){
casa.mover();
repaint();
}
public class teclado extends KeyAdapter{
public void keyReleased(KeyEvent e){
casa.KeyReleased(e);
}
public void keyPressed(KeyEvent e){
casa.KeyPressed(e);
}
}
}
Saludos.