Quiero mover un objeto Graphics g.
Tengo 3 clases.
Mi main
Código:
Mi ventana public class lavivorita { public static void main(String[] args) { ventana v = new ventana(); } }
Código:
import javax.swing.JFrame; public class ventana extends JFrame { public ventana () { super("Graficos"); this.setSize(405,408); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); definirGraficos(); this.setResizable(false); this.setVisible(true); } public void definirGraficos() { lista p = new lista (); add(p); } }
hasta todo bien, y ahora:
Mi clase de gráficos
Código:
import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JPanel; public class lista extends JPanel implements KeyListener { public lista() { setSize(405,408); this.addKeyListener(this); } int x=202,y=202; public void paintComponent (Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, 400, 376); g.setColor(Color.WHITE); g.drawLine(400,25,0,25); g.drawLine(400,50,0,50); g.drawLine(400,75,0,75); g.drawLine(400,100,0,100); g.drawLine(400,125,0,125); g.drawLine(400,150,0,150); g.drawLine(400,175,0,175); g.drawLine(400,200,0,200); g.drawLine(400,225,0,225); g.drawLine(400,250,0,250); g.drawLine(400,275,0,275); g.drawLine(400,300,0,300); g.drawLine(400,325,0,325); g.drawLine(400,350,0,350); g.drawLine( 25, 0, 25, 400 ); g.drawLine( 50, 0, 50, 400 ); g.drawLine( 75, 0, 75, 400 ); g.drawLine( 100, 0, 100, 400 ); g.drawLine( 125, 0, 125, 400 ); g.drawLine( 150, 0, 150, 400 ); g.drawLine( 175, 0, 175, 400 ); g.drawLine( 200, 0, 200, 400 ); g.drawLine( 225, 0, 225, 400 ); g.drawLine( 250, 0, 250, 400 ); g.drawLine( 275, 0, 275, 400 ); g.drawLine( 300, 0, 300, 400 ); g.drawLine( 325, 0, 325, 400 ); g.drawLine( 350, 0, 350, 400 ); g.drawLine( 375, 0, 375, 400 ); g.setColor(Color.red); g.fillRect(x, y, 22, 22); } public void keyTyped(KeyEvent e) { //Cuando se preciona una tecla y se mantiene precionada } public void keyPressed(KeyEvent e) {//Cuando se suelta la tecla if(e.getKeyCode()==KeyEvent.VK_UP){ y+=3; x+=3; this.repaint(); } } public void keyReleased(KeyEvent e) { //La primera ves que se preciona } }
Lo único que hago es decirle que al presionar arriba me modifique X, Y para que se mueva el objeto, nada mas :(
Ayudaa