Hi. I have made a code that should allowed me to move an object in a frame, using the arrow keys. But I don't know why, is not working. So I hope that you know what I did wrong.
package joc; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; /** * * @author Paul */ public class obiect extends JPanel implements ActionListener, KeyListener { Timer tm = new Timer(5,this); int x = 0, y = 0, velX = 0, velY = 0; public obiect() { tm.start(); addKeyListener(this); setFocusable(true); // enable keylistener setFocusTraversalKeysEnabled(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.CYAN); g.fillRect(x,y,50,30); tm.start(); /* ImageIcon i = new ImageIcon("car.png"); i.paintIcon(this, g, 100, 100); */ } @Override public void actionPerformed(ActionEvent e) { if(x<0){ velX = 0; x = 0; } if(x>500) { velX = 0; x = 530; } if(y<0){ velY=0; y=0; } if(y>500) { velY=0; y=500; } x = x + velX; // dreapta sau stanga y = y + velY; // sus sau jos repaint(); } @Override public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); if(c == KeyEvent.VK_LEFT) { velX= -1; velY = 0; } if(c == KeyEvent.VK_UP) { velX=0; velY=-1; } if(c == KeyEvent.VK_RIGHT) { velX=1; velY=0; } if(c == KeyEvent.VK_DOWN) { velX=0; velY=1; } } @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { velX=0; velY=0; } }
The main program is:
package joc; import javax.swing.JFrame; /** * * @author paul */ public class Joc { public static void main(String[] args) { obiect o = new obiect(); JFrame frame = new JFrame("Proiect Diacu Paul"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setSize(500,500); frame.setVisible(true); frame.add(o); } }