使用箭头键旋转图像

时间:2018-04-05 19:04:55

标签: java jframe jpanel keylistener

我正在尝试制作一款使用箭头键移动汽车(即图像)的赛车游戏。当我单击左箭头键时,我希望图像旋转一定的度数以显示汽车正在转动。出于某种原因,当点击左箭头键并且没有显示任何错误消息时,汽车没有转动。我将非常感谢您提供的任何帮助,并提前致谢!

//GameClass:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;


public class Game extends JPanel implements KeyListener {
   private Image image;
   BufferedImage images;
   private Image image2;
   private int x1, y1, velx = 0, vely = 0;
   ImageIcon I2;
   private Graphics2D g2;

   public Game() {
      x1 = 100;
      y1 = 100;
}

public void paint(Graphics g) {

    ImageIcon I = new ImageIcon("track.jpg");
    image = I.getImage();
    I2 = new ImageIcon("RedCar.png");
    image2 = I2.getImage();
    g.drawImage(image, 0, 0, null);
    g.drawImage(image2,x1,y1,25,14,null);
    repaint();
}
  @Override
  public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT) {
        try {
              File url = new File("RedCar.png");
              images = ImageIO.read(url);
          }
          catch(Exception r) {
              r.printStackTrace();
       }

           Graphics g = images.getGraphics();
           Graphics2D g2d = (Graphics2D)g;
           g2d.rotate(Math.toRadians(15));


       }
       repaint();
       if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
           x1 += 5;
           velx = 1;
           vely = 0;
      }
       if (e.getKeyCode() == KeyEvent.VK_UP) {
           y1 -= 5;
           velx = 0;
          vely = -1;
     }
       if (e.getKeyCode() == KeyEvent.VK_DOWN) {
           y1 += 5;
           velx = 0;
           vely = 1;
       }
  }

   @Override
   public void keyReleased(KeyEvent e) {
       vely = 0;
       velx = 0;
   }

   @Override
   public void keyTyped(KeyEvent e) {
       // TODO Auto-generated method stub

   }
}

//GameDemo Class:
import javax.swing.*;
public class GameDemo {
    public static void main(String[] args) {
        Game game = new Game();
        JFrame frame = new JFrame();
        frame.setTitle("The Race");
        frame.setSize(600, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(game);
        frame.addKeyListener(game);
        frame.setResizable(false);
   }
   }

0 个答案:

没有答案