I am trying to make a racing game which uses the arrow keys to move the car(which is a image). When I click the left arrow key I want the image to rotate a certain amount of degrees to show that the car is turning. For some reason the car isn’t turning when the left arrow key is clicked and isn’t showing any error messages either. I would appreciate any help that you can give and thanks in advance!
//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);
}
}
Related
So, I am using ImageIcon and Image to animate a character. So far my code makes it look like the character is running however for a reason that I can't figure out KeyListener is not working. I have been at this for a while and I am wondering what I am doing wrong. This is my code:
*Right now I took out moving up and down because I couldn't get side to side to work. velyY was going to be the change in y.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Image;
public class Main extends JPanel implements ActionListener,KeyListener{
ImageIcon images[];
int x = 100;
int y = 5;
int velX;
int velY;
int totalImages =3, currentImage = 0, animationDelay = 160;
Timer animationTimer;
public Main() {
images = new ImageIcon[totalImages];
images[0] = new ImageIcon("standing.png");
images[1] = new ImageIcon("ready.png");
images[2] = new ImageIcon("running.png");
startAnimation();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2 = (Graphics) g;
if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE){
Image img = images[currentImage].getImage();
g2.drawImage(img, x, 407, null);
currentImage = (currentImage + 1) % totalImages;
}
}
public void actionPerformed(ActionEvent e) {
repaint();
x+=velX;
}
public void right(){
velX = 8;
}
public void left(){
velX = -8;
}
public void keyPressed(KeyEvent arg0) {
int code = arg0.getKeyCode();
if (code == KeyEvent.VK_A){
left();
}
if(code == KeyEvent.VK_D){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
velX = 0;
velY = 0;
}
public void startAnimation() {
if (animationTimer == null) {
currentImage = 0;
animationTimer = new Timer(animationDelay, this);
animationTimer.start();
} else if (!animationTimer.isRunning())
animationTimer.restart();
}
public void stopAnimation() {
animationTimer.stop();
}
}//end class
You have to register your KeyListener to your panel, if you want it to manage key events.
The second thing is that a JPanel is not focusable by default, so you have to make it focusable to receive key events.
In your Main constructor, just add :
setFocusable(true); // make your panel focusable
addKeyListener(this); // register the key listener
I should be able to move the rectangle with the arrow keys but after running the program a few times the rectangle does not move. To make the rectangle move I close Netbeans and reopen it. Then the rectangle is able to move but it stops moving after a couple tries. I want to solve this problem so I can make changes.
package project;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
//KeyListener is use with keyboard
public class main extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this); //for animation
int x = 50, y = 50, velX =0, velY = 0;
public main()
{
tm.start(); //starts timer
addKeyListener(this); //this refearing to KeyListener
setFocusable(true); //enable KeyListener
setFocusTraversalKeysEnabled(false); //shift or tab is not use so F
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,y,50,50);
}
public void actionPerformed(ActionEvent e)
{
if (x<0)
{
velX = 0;
x = 0;
}
if (x>500)
{
velX = 0;
x = 500;
}
if (y<0)
{
velY = 0;
y=0;
}
if (y>300)
{
velY = 0;
y = 300;
}
x = x + velX;
y = y + velY;
repaint(); // repaint rectangle
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode(); //get key
if (c == KeyEvent.VK_LEFT) // VK_Left is left arrow
{
velX = -3;
velY = 0;
}
if (c == KeyEvent.VK_UP) // VK_UP is up arrow
{
velX = 0;
velY = -3; // means up
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 3;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 3;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) //when you stop pressing
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
main m = new main();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(m);
}
}
I have the following code to show you:
public class Test extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public Test()
{
tm.start(); //starts the timer
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint(Graphics g)
{
super.paint(g);
ImageIcon s = new ImageIcon("C:\\Users\\Owner\\Pictures\\Stick.jpg");
s.paintIcon(this,g,x,y);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
if (x > 630)
{
velX = 0;
x = 630;
}
if(y < 0)
{
velY = 0;
y = 0;
}
if(y > 430)
{
velY = 0;
y = 430;
}
x = x + velX;
y = y + velY;
repaint();
}
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;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
Test t = new Test();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(700, 600);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
jf.setVisible(true);
}
My problem is I whenever the user holds the right arrow on the keyboard it changes an image, when the user lets go it goes back the the default image. Please tell me how to do that. I think it is a series of if statements in the Graphics class then calling them to the key input but I'm not quite sure. I am also using Eclipse. Thank You.
Override paintComponent instead of paint. See Performing Custom Painting and Painting in AWT and Swing for more details
Use the key bindings API instead of KeyListener, it will cause you less issues. See How to Use Key Bindings for more details
Essentially, you could just have a Image as a class instance field, which was painted by the paintComponent method. When the key was pressed, you would change the image to the "move image" and when it was released, change it back to the "default image"
Updated with example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Mover {
public enum Direction {
LEFT, RIGHT, NONE;
}
public void setDirection(Direction direction);
public Direction getDirection();
}
public class TestPane extends JPanel implements Mover {
private BufferedImage left;
private BufferedImage right;
private BufferedImage stand;
private BufferedImage current;
private Direction direction = Direction.NONE;
private int xPos;
private int yPos;
public TestPane() {
try {
left = ImageIO.read(getClass().getResource("/Left.png"));
right = ImageIO.read(getClass().getResource("/Right.png"));
stand = ImageIO.read(getClass().getResource("/Stand.png"));
current = stand;
xPos = 100 - (current.getWidth() / 2);
yPos = 100 - (current.getHeight() / 2);
} catch (IOException exp) {
exp.printStackTrace();
}
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), new MoveAction(this, Direction.LEFT));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), new MoveAction(this, Direction.NONE));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "move.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), new MoveAction(this, Direction.RIGHT));
bindKeyStrokeTo(WHEN_IN_FOCUSED_WINDOW, "stop.right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), new MoveAction(this, Direction.NONE));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updatePosition();
repaint();
}
});
timer.start();
}
protected void bindKeyStrokeTo(int condition, String name, KeyStroke keyStroke, Action action) {
InputMap im = getInputMap(condition);
ActionMap am = getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
#Override
public Direction getDirection() {
return direction;
}
#Override
public void setDirection(Direction direction) {
this.direction = direction;
}
protected void updatePosition() {
switch (getDirection()) {
case LEFT:
current = left;
xPos -= 1;
break;
case RIGHT:
current = right;
xPos += 1;
break;
case NONE:
current = stand;
break;
}
if (xPos < 0) {
xPos = 0;
current = stand;
} else if (xPos + current.getWidth() > getWidth()) {
current = stand;
xPos = getWidth() - current.getWidth();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(current, xPos, yPos, this);
g2d.dispose();
}
}
public class MoveAction extends AbstractAction {
private Mover mover;
private Mover.Direction direction;
public MoveAction(Mover mover, Mover.Direction direction) {
this.mover = mover;
this.direction = direction;
}
#Override
public void actionPerformed(ActionEvent e) {
mover.setDirection(direction);
}
}
}
Hi I am new to making games, and I am working on one for a project. My code however does not make the Ship image move. Can someone help with a reasonable and simple explanation? Maybe even explain how to do this a bit simpler?
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.geom.*;
import java.util.Random;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SpaceJam extends JPanel implements ActionListener
{
private Timer time;
private ImageIcon Ship = new ImageIcon("Spaceship.PNG");
private ImageIcon Back = new ImageIcon("background.PNG");
private ImageIcon Test = new ImageIcon("test.PNG");
private int x, y, dx, dy;
private Image CurrentImage = Ship.getImage();
public SpaceJam()
{
addKeyListener(new AL());
setFocusable(true);
x = 100;
y = 100;
dx = 0;
dy = 0;
time = new Timer(100, this);
time.start();
}
public void actionPerformed(ActionEvent e)
{
repaint();
move();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(Back.getImage() ,0,0,null);
g2d.drawImage(CurrentImage, x, y, null);
}
public void move()
{
x += dx;
y += dy;
}
public class AL extends KeyAdapter
{
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT)
{
dx = 5;
move();
}
if (key == KeyEvent.VK_LEFT)
{
dx = -5;
move();
}
}
}
}
So I have am trying to make a keyListener for the arrow keys that responds to the arrow keys, and can handle multiple keys at once. I am trying to put the keys pressed into an ArrayList, and then handle them in my repaint() method. However, I have a problem. I am unsure where to add the keys, and where to remove them. I am not looking so much for a code solution as much as the logic that should go behind this.
//graham
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Arrows extends JPanel implements KeyListener {
private int c = 0;
private int x = 250;
private int y = 250;
private static ArrayList<Integer> keys = new ArrayList<Integer>();
public Arrows() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
//*********
//need to update to make so can press (and hold) multiple different keys at once
//*********
g.setColor(Color.WHITE);
g.fillRect(x, y , 20, 20);
for(int i = 0; i < keys.size(); i++){ //********> only want to handle one at a time
//handle each key
c = keys.get(i);
switch(c){
case 37:
//left arrow
x -= 10;
keys.remove(i);
break;
case 38:
// up arrow
y -= 10;
keys.remove(i);
break;
case 39:
//right arrow
x += 10;
keys.remove(i);
break;
case 40:
//down arrow
y += 10;
keys.remove(i);
break;
}
}
g.setColor(Color.BLUE);
g.fillRect(x, y, 20, 20);
}
public void keyPressed(KeyEvent e) {
//******
//need to create a list of keys pressed, then process them in the repaint. Later delete them after pressed
//******
keys.add(e.getKeyCode());
//repaint();
}
public void keyReleased(KeyEvent e) {
//****
//here need to repaint --- need to correct to do something proper later --- due to holding down a key teleports..
//****
repaint();
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] s) {
JFrame f = new JFrame();
f.getContentPane().add(new Arrows());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
//need to null out keys
keys.add(65);
}
}
Here see if you can use my code as an example. They're fairly similar.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 1000);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_UP) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_LEFT) {
velx = -1;
}
{
if (code == KeyEvent.VK_RIGHT) {
velx = 1;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}