I have an image and I want that when I press the left arrow, image turns to the left. In methods that are already created (up, down), you don't have to hold the button to turn around or for increasing speed. It's enough to press it once and the method will be applied. Here's my code:
import java.awt.Graphics; import java.awt.Image; 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; public class obiect extends JPanel implements ActionListener, KeyListener { private int viteza=25; Timer tm = new Timer(viteza,this); int x = 480, y = 430, velX = 0, velY = 0; ImageIcon imageIcon = new ImageIcon("/home/diacu/Documents/joc/src/joc/car.png"); Image image = imageIcon.getImage(); ImageIcon imageIcon1 = new ImageIcon("/home/diacu/Documents/joc/src/joc/car1.png"); Image image1 = imageIcon1.getImage(); public obiect() { addKeyListener(this); setFocusable(true); // enable keylistener setFocusTraversalKeysEnabled(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, x, y, this); setOpaque(false); } public void up() { velX=0; velY=-1; tm.stop(); tm.setDelay(viteza); viteza--; tm.start(); } public void down() { velX=0; velY=1; tm.stop(); viteza=25; } public void left() { velX=-1; velY=0; } public void right() { velX=1; velY=0; } @Override public void actionPerformed(ActionEvent e) { if(x<0) { velX = 0; x = 480; y=430; System.out.println("Well done! I've never seen such a worst driver as you are :)"); } if(x>480) { velX = 0; y=430; x = 480; System.out.println("Well done! I've never seen such a worst driver as you are :)"); } if(y<0) { velY=0; y=430; x=480; System.out.println("Well done! I've never seen such a worst driver as you are :)"); } if(y>430) { velY=0; y=430; x=480; System.out.println("Well done! I've never seen such a worst driver as you are :)"); } repaint(); x = x + velX; y = y + velY; } @Override public void keyPressed(KeyEvent e) { int tasta = e.getKeyCode(); int tasta2 = e.getKeyCode(); tm.start(); if(tasta == KeyEvent.VK_LEFT) { left(); } if(tasta == KeyEvent.VK_UP) { up(); } if(tasta == KeyEvent.VK_RIGHT) { right(); } if(tasta == KeyEvent.VK_DOWN) { down(); } } @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { } }