0

Help me please, I need to rotate image by pressing the button. At the moment, I have movement but I don't know how to make the image change. I imagined that if I press the left arrow is drawn figure such left.png etc.

package CarGame;

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.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class CarGame extends JPanel implements ActionListener, KeyListener
{
  Timer timer = new Timer(5, this);
  int x = 0;
  int y = 0;
  int a = 0;
  int b = 0;

  public CarGame()
  {
    this.timer.start();
    addKeyListener(this);
    setFocusable(true);
    setBackground(Color.WHITE);
  }

  @Override
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    ImageIcon i = new ImageIcon(getClass().getResource("right.png"));

    g.drawImage(i.getImage(), this.x, this.y, this);
  }

  @Override
  public void actionPerformed(ActionEvent e)
  {
    if (this.x < 0)
    {
      this.a = 0;
      this.x = 0;
    }
    if (this.x > 865)
    {
      this.a = 0;
      this.x = 865;
    }
    if (this.y < 0)
    {
      this.b = 0;
      this.y = 0;
    }
    if (this.y > 490)
    {
      this.b = 0;
      this.y = 490;
    }
    this.x += this.a;
    this.y += this.b;
    repaint();
  }

  @Override
  public void keyPressed(KeyEvent e)
  {
    int c = e.getKeyCode();
    if (c == 37)
    {
      this.a = -1;
      this.b = 0;
    }
    if (c == 38)
    {
      this.a = 0;
      this.b = -1;
    }
    if (c == 39)
    {
      this.a = 1;
      this.b = 0;
    }
    if (c == 40)
    {
      this.a = 0;
      this.b = 1;
    }
  }

  @Override
  public void keyTyped(KeyEvent e) {}

  @Override
  public void keyReleased(KeyEvent e)
  {
    this.a = 0;
    this.b = 0;
  }

  public static void main(String[] args)
  {
    CarGame cg = new CarGame();
    JFrame jf = new JFrame();
    jf.setTitle("");
    jf.setSize(1024, 600);
    jf.setResizable(false);
    jf.setLocationRelativeTo(null);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(3);
    jf.add(cg);
  }
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • Please reduce your code and post only the necessary as a [MCVE] – Khalil Khalaf Apr 19 '16 at 15:48
  • This has already been answered: http://stackoverflow.com/a/8639615/912829 – ACV Apr 19 '16 at 16:21
  • This is not exactly what I need it, I need that when you press the Left arrow, so we will draw a different picture than is currently being rendered. Something like "if (keyCode == 38) { ImageIcon i = new ImageIcon (getClass (). GetResource ("left.png")); } – Abdul Nasralah Apr 19 '16 at 17:07

0 Answers0