Java key event not working - java

Hello i am trying to make the game pong. Now i am trying to move the paddle with my keyboard but it is not responding at all. Can anyone tell me what i am missing here? I can't figure it out what it is i am doing wrong.
The paddle is moving when i set the condition in the check to false so there is not a problem in moving it. Just getting the keyEvent to work.
What am i missing in the keyEvent?
Thanks in advance!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Paneel extends JPanel
{
private int height, width;
private boolean moveLeft, moveRight, moveUp, moveDown, playerMoveLeft,
playerMoveRight, computerMoveLeft, computerMoveRight = false;
private Timer timer;
private Ball ball;
private Paddle player, computer;
public Paneel()
{
ball = new Ball(994, 772);
player = new Paddle(1, 994, 722);
computer = new Paddle(2, 944, 722);
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
}
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
ball.drawBall(pen);
player.drawPaddle(pen);
computer.drawPaddle(pen);
pen.drawString("" + getHeight() + " " + getWidth(), 50, 50);
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight =
true;
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight =
false;
}
public void movePlayer()
{
if (playerMoveRight == true) player.moveDown();
else if (playerMoveLeft == true) player.moveUp();
}
public void moveComputer()
{
}
public void resetBall()
{
}
public void resetPlayer()
{
}
public void resetComputer()
{
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
movePlayer();
repaint();
}
}
}

Related

Java KeyListener not responding at all

I am trying to make the game pong but i am having trouble with the KeyListener not working. What is wrong with the KeyListener? It is just not working and everything i look up doesn't work for me. It seems to work for other people.
Am i using it in the wrong place?
I hope anyone can help me with this.
Thanks in advance!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Paneel extends JPanel
{
private int height, width;
private boolean moveLeft, moveRight, moveUp, moveDown, playerMoveLeft, playerMoveRight, computerMoveLeft, computerMoveRight;
private Timer timer;
private Ball ball;
private Paddle player, computer;
public Paneel()
{
ball = new Ball(994, 772);
player = new Paddle(1, 994, 722);
computer = new Paddle(2, 944, 722);
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight = true;
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight = false;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
}
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
ball.drawBall(pen);
player.drawPaddle(pen);
computer.drawPaddle(pen);
}
public void movePlayer()
{
if (playerMoveRight == true) player.moveDown();
else if (playerMoveLeft == true) player.moveUp();
}
public void moveComputer()
{
}
public void resetBall()
{
}
public void resetPlayer()
{
}
public void resetComputer()
{
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
movePlayer();
repaint();
}
}
}
set focus on your panel by requestFocus(); i hop that will solve the problem

Key listener not detecting key presses?

I am trying to make my picture move based on the arrow keys being pressed but the key listener is not detecting any key presses. I attached the code for the panel which i add to a frame in a driver.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class RacePanel extends JPanel
{
//variables
private ImageIcon backGround = new ImageIcon("images/back.png");
private Penguin p;
private ImageIcon icon1 = new ImageIcon("images/PenguinR.png");
private ImageIcon icon2 = new ImageIcon("images/PenguinL.png");
private int x = 10;
//move left and right methods
public void moveLeft(Penguin x)
{
x.setImageIcon(icon2);
x.setX(x.getX() - 5);
}
public void moveRight(Penguin x)
{
x.setImageIcon(icon1);
x.setX(x.getX() + 5);
}
public RacePanel()
{
JPanel RacePanel = new JPanel();
super.addKeyListener(new Key());
setFocusable(true);
p = new Penguin();
Timer t = new Timer(50, new Listener());
t.start();
}
private class Key implements KeyListener
{
public Key()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
moveRight(p);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
moveLeft(p);
}
if(e.getKeyCode() == KeyEvent.VK_UP)
{
System.out.println("i am listening");
}
repaint();
}
public void keyReleased(KeyEvent e)
{
}
}
//graphics
public void paintComponent(Graphics g)
{
g.drawImage(backGround.getImage(),0,0,800,600,null);
g.drawImage(p.getImageIcon().getImage(),p.getX(),p.getY(),50,100,null);
}
//action listener .05 second loop
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
}
I know that it is not recognizing key pressed because i added a line of code to print "i am listening" if the up arrow is pressed and nothing prints.
I also know the issue is not because of the timer cause i tested it by adding the moveRight method to the actionPerformed method.

Java Game: Shooting Bullets

I am (kind of) new to creating games with Java. I created some simple games before like a bag collecting game but now I want to make a top-down zombie shooting game. I already have a player that can move, but now I want to implement shooting. The problem is that I am not sure how to make a new bullet that shoots from the player to the right / up / down /left to the end of the screen depending on what part of the screen the player is facing.
I have pasted all my of code below (4 classes):
package me.mateo226.main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import me.mateo226.entities.Player;
import me.mateo226.guns.Bullet;
public class GamePanel extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private static final int PWIDTH = 720;
private static final int PHEIGHT = 480;
private static Thread game;
private static volatile boolean running = false;
public static volatile boolean gameOver = false;
public static volatile boolean paused = false;
public static Graphics g;
public static Image gImage;
public static long lastLoopTime = System.currentTimeMillis();
public static long delta;
public static volatile boolean upPressed = false;
public static volatile boolean downPressed = false;
public static volatile boolean leftPressed = false;
public static volatile boolean rightPressed = false;
public BufferedImage backgroundImage;
public Player player;
Bullet bullet;
public GamePanel() {
setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
setBackground(Color.white);
setFocusable(true);
requestFocus();
waitForTermination();
}
public void addNotify() {
super.addNotify();
startGame();
}
public void waitForTermination() {
addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE) {
GamePanel.stopGame();
}
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
upPressed = true;
}
if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
downPressed = true;
}
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
leftPressed = true;
}
if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
if (keyCode == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP) {
upPressed = false;
}
if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN) {
downPressed = false;
}
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
});
}
#Override
public void run() {
running = true;
while (running) {
delta = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
gameUpdate();
gameRender();
checkMovement();
paintpauseScreen();
try {
Thread.sleep(5);
} catch (Exception e) {
System.out.println("The thread couldn't sleep! Error info: "
+ e);
}
}
System.exit(0);
}
private void checkMovement() {
if (!paused && !gameOver) {
}
}
private void paintpauseScreen() {
Graphics g;
try {
g = this.getGraphics();
if ((g != null) && (gImage != null))
g.drawImage(gImage, 0, 0, null);
g.dispose();
} catch (Exception e) {
System.out.println("Graphics context error: " + e);
}
}
private void gameRender() {
if (gImage == null) {
gImage = createImage(PWIDTH, PHEIGHT);
if (gImage == null) {
System.out
.println("image null after creating it??? Please check the code for any errors!");
} else {
g = gImage.getGraphics();
}
}
if (!paused) {
g.setColor(Color.white);
g.fillRect(0, 0, PWIDTH, PHEIGHT);
g.setColor(Color.blue);
}
try {
backgroundImage = ImageIO.read(new File("res\\background.png"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(backgroundImage, 0, 0, Color.white, null);
if (player != null) {
player.drawPlayer(g);
}
if (bullet != null) {
bullet.drawBullet(g);
}
}
private void gameUpdate() {
if (!paused && !gameOver) {
movePlayer();
if (bullet != null){
bullet.shootBullet(g, "right");
}
}
}
public void startGame() {
if (game == null) {
game = new Thread(this);
if (game == null) {
System.out.println("Couldn't create the thread!");
} else {
System.out.println("Thread created!");
game.start();
}
}
if (g == null) {
g = this.getGraphics();
if (g == null) {
System.out.println("The graphics were not created!");
} else {
System.out.println("The graphics are successfully created!");
}
}
player = new Player(32, 32, "res\\player.png");
bullet = new Bullet("res\\grassTile.png", "right", player.x + 32,
player.y);
running = true;
}
public void movePlayer() {
if (upPressed) {
player.y -= player.moveSpeed * delta;
}
if (downPressed) {
player.y += player.moveSpeed * delta;
}
if (leftPressed) {
player.x -= player.moveSpeed * delta;
}
if (rightPressed) {
player.x += player.moveSpeed * delta;
}
}
public static void stopGame() {
running = false;
}
}
This was my GamePanel class.
This is my Main class:
package me.mateo226.main;
import java.awt.Container;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main extends JFrame implements WindowListener {
private static final long serialVersionUID = 1L;
private static GamePanel panel;
public static boolean DEBUGGING = false;
public Main(){
super("The Gun Reactor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(this);
Container c = getContentPane();
panel = new GamePanel();
c.add(panel, "Center");
setResizable(false);
pack();
setLocationRelativeTo(null);
if(JOptionPane.showConfirmDialog(null, "Enable debugging?") == 1){
DEBUGGING = true;
} else {
DEBUGGING = false;
}
setVisible(true);
}
#Override
public void windowActivated(WindowEvent arg0) {
}
#Override
public void windowClosed(WindowEvent arg0) {
}
#Override
public void windowClosing(WindowEvent arg0) {
}
#Override
public void windowDeactivated(WindowEvent arg0) {
}
#Override
public void windowDeiconified(WindowEvent arg0) {
}
#Override
public void windowIconified(WindowEvent arg0) {
}
#Override
public void windowOpened(WindowEvent arg0) {
}
public static void main(String args[]){
new Main();
}
}
This is my Player class:
package me.mateo226.entities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player {
public int x, y;
public float moveSpeed = 0.1f;
private BufferedImage playerTexture;;
public Player(int x, int y, String texturePath){
this.x = x;
this.y = y;
try {
playerTexture = ImageIO.read(new File(texturePath));
} catch (IOException e){
e.printStackTrace();
}
}
public void drawPlayer(Graphics g){
g.setColor(Color.white);
g.drawImage(playerTexture, x, y, null);
}
}
And finally this is my bullet class which I don't really know how to use or even make it properly:
package me.mateo226.guns;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import me.mateo226.main.GamePanel;
public class Bullet {
private int x, y;
private BufferedImage bulletTexture;
private float bulletSpeed = 0.1f;
public Bullet(String bulletTexturePath, String dir, int x, int y) {
this.x = x;
this.y = y;
try {
bulletTexture = ImageIO.read(new File(bulletTexturePath));
} catch (IOException e) {
e.printStackTrace();
}
}
public void drawBullet(Graphics g) {
g.setColor(Color.white);
g.drawImage(bulletTexture, x, y, null);
}
public void shootBullet(Graphics g, String dir) {
switch (dir) {
case "left":
while (x > -32) {
x -= bulletSpeed * GamePanel.delta;
drawBullet(g);
}
break;
case "right":
while (x < 700) {
x += bulletSpeed * GamePanel.delta;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
case "up":
while (y > -32) {
y -= bulletSpeed * GamePanel.delta;
drawBullet(g);
}
break;
case "down":
while (y < 480) {
y += bulletSpeed * GamePanel.delta;
drawBullet(g);
}
break;
}
}
}
Any help would be great! Thank you very much!
EDIT
I just read that you only have four directions. In that case you do not need a direction vector. Just set the direction once.
Ok so the code example.
First the gameloop. Add the firedBullets for update in the gameloop. Every fired bullet gets moved on its direction vector.
private void gameUpdate() {
if (!paused && !gameOver) {
movePlayer();
foreach(Bullet bullet : player.getFiredBullets(){
bullet.moveInDirection();
}
}
}
And your Bullet class:
public class Bullet {
private Direction direction;
private float speed = 1.2f;
private int x;
private int y;
public Bullet(int x, int y){
this.x =x;
this.y=y;
}
public void launchBullet(Direction direction){
this.direction=direction;
}
public void moveInDirection() {
//move the bullet with speed in the set direction. Same as you already have but without the while loop.
}
}
So the player should have a method fire.
This creates the bullet with position of the player. The bullet gets the same direction as where the player is facing. And the bullet get added to the list so it will be updated every gameloop.
public class Player {
private List<Bullet> firedBullets = new ArrayList<Bullet>();
public void fire(){
Bullet bullet = new Bullet(playerX, playerY);
firedbullets.add(bullet);
bullet.launch(direction); //this should be calculated by which direction the player is facing.
}
}
So the direction gets set once when the bullet is fired. Every game update the bullet is moved in this direction by the speed of the bullet. This logic can be used for everything that has to be moved in the game. For example if you want a bullet that changes direction in mid-air you would just change its direction in mid-air.

Java code shows no errors, but JFrame won't show

I have a project due in a couple days, and my code in Eclipse shows no errors, and no warnings, how ever the game(JFrame) wont show up. I believe the error has to do with the way I've done the movement
this.addKeyListener(movement);
Any ideas are welcome!
Main.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Main extends JFrame implements Runnable {
private Movement movement = new Movement();
public int width = 800;
public int height = 600;
public int fps = 1000;
public int score;
public int charX;
public int charY;
public int charUp;
public int charDown;
public int charLeft;
public int charRight;
public int movementSpeed = 5;
public int movementFrame = 0;
public int movementDiagonal = 10;
public boolean bCharUp = false;
public boolean bCharDown = false;
public boolean bCharLeft = false;
public boolean bCharRight = false;
public Color cytoplasm = new Color(50,130,255);
public Image character;
public Thread game;
//Double Buffer
private Image dbImage;
private Graphics dbg;
public Main() {
//Images
ImageIcon characterImage = new ImageIcon("F:/workplace/com.thecellsells.lysosome/src/com/thecellsells/lysosome/Lysosome.gif");
character = (characterImage.getImage());
//Game Properties
setSize(width, height);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(cytoplasm);
this.addKeyListener(movement);
//Threads
game = new Thread(this);
game.start();
//Other
charY = height/2 - 10;
charX = width/2 - 16;
}
public void paint(Graphics g) {
//Double Buffer
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.drawImage(character, charX, charY, this);
repaint();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Main Main = new Main();
}
#Override
public void run() {
while (true) {
fpsSetter();
}
}
//FPS -- set's how fast game runs
#SuppressWarnings("static-access")
public void fpsSetter() {
try {
game.sleep(fps/fps);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Movement.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
#SuppressWarnings("serial")
public class Movement extends Main implements KeyListener {
public int charUp;
public int charDown;
public int charLeft;
public int charRight;
public int movementSpeed = 5;
public int movementFrame = 0;
public int movementDiagonal = 10;
public boolean bCharUp = false;
public boolean bCharDown = false;
public boolean bCharLeft = false;
public boolean bCharRight = false;
public void keyPressed (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W ) {
bCharUp = true;
if (bCharUp) {
charY -= 1;
}
}
if (e.getKeyCode() == KeyEvent.VK_A) {
bCharLeft = true;
if (bCharLeft) {
charX -=1;
}
}
if (e.getKeyCode() == KeyEvent.VK_W ) {
bCharDown = true;
if (bCharDown) {
charY -=1;
}
}
if (e.getKeyCode() == KeyEvent.VK_D) {
bCharRight = true;
if (bCharRight) {
charX +=1;
}
}
}
#Override
public void keyReleased (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W ) {
bCharUp = false;
}
if (e.getKeyCode() == KeyEvent.VK_A) {
bCharLeft = false;
}
if (e.getKeyCode() == KeyEvent.VK_S) {
bCharDown = false;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
bCharRight = false;
}
}
#Override
public void keyTyped(KeyEvent e) { }
}
Thomas
Try using setPreferredSize(width, height);.
EDIT:
The problem lies in that you extended the Main class in the Movement class. So when you start the program, the movement class calls the Main class and that initializes the Movement class again, making a race condition. Just dont extend the Main class and make variables charX and charY static. Thus you can access the variables anywhere using Main..
In your main() method, you are creating the Main object (which extends from JFrame) but you haven't set it visible.

When I move the screen it gets torn apart

So, I just added the InputHandler so I can move my screen with wasd (up,down,left,right). but when I try it my spritesheet gets torn apart and the screen does not move up or down, just diagonally (left and right works fine) and I dont know why it does this. I dont have any errors...
package ca.linus.game;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
public class InputHandler implements KeyListener {
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private int numTimesPressed = 0;
private boolean pressed = false;
public int getNumTimesPressed() {
return numTimesPressed;
}
public boolean isPressed() {
return pressed;
}
public void toggle(boolean isPressed) {
pressed = isPressed;
if (isPressed) numTimesPressed++;
}
}
public List<Key> keys = new ArrayList<Key>();
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int keyCode, boolean isPressed) {
if (keyCode == KeyEvent.VK_W) {up.toggle(isPressed);}
if (keyCode == KeyEvent.VK_S) {down.toggle(isPressed);}
if (keyCode == KeyEvent.VK_D) {right.toggle(isPressed);}
if (keyCode == KeyEvent.VK_A) {left.toggle(isPressed);}
}
}
Here's my InputHandler file.
All help appreciated!

Categories

Resources