Java KeyListener not responding at all - java

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

Related

Java key event not working

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();
}
}
}

How to make smooth animations in java swing

Hi I'm using the Timer class and the repaint method for the JPanel, but whenever I hit DOWN and the space ship moves halfway down the screen, it shrinks and stays in place. It never reaches the bottom of the window. It is the same when I move it to the RIGHT.
Also when I try to place it in a differnt y position, the background isn't black anymore. Can someone help me with this please? Here is a sample of my code:
package javapaint;
import java.awt.Color;
import java.awt.EventQueue;
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 java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SpaceShipFlight
{
private JFrame windowFrame;
private BufferedImage shipSprite;
private BufferedImage spaceBackground;
/** MAIN METHOD **/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
SpaceShipFlight window = new SpaceShipFlight();
window.windowFrame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/** CONSTRUCTOR **/
public SpaceShipFlight() throws IOException
{
/*************************************************************************
SPACE SHIP FLIGHT JFRAME
*************************************************************************/
windowFrame = new JFrame("Space Ship Flight");
windowFrame.setBounds(0, 0, 950, 700);
windowFrame.setBackground(Color.BLACK);
/*************************************************************************
SPACE SHIP FLIGHT SPRITES (FOR DRAWING)
*************************************************************************/
spaceBackground = ImageIO.read(new File("Space (Medium).png"));
// 450 x 374
shipSprite = ImageIO.read(new File("Ship Sprite.png"));
// 64 x 64 png of space ship
/*************************************************************************
SPACE SHIP FLIGHT JPANEL (FOR DRAWING)
*************************************************************************/
SpacePanel spacePanel = new SpacePanel();
windowFrame.add(spacePanel);
/*************************************************************************
SPACE SHIP FLIGHT TIMER
*************************************************************************/
Timer timer = new Timer(10, new AnimationListener(spacePanel));
timer.start();
/*************************************************************************
EVENT HANDLER TO MOVE SPACE SHIP
*************************************************************************/
/*
EventHandler <KeyEvent> moveShip = new EventHandler<KeyEvent> ()
{
#Override
public void handle(KeyEvent event)
{
if (event.getCharacter().equalsIgnoreCase("X"))
{
spacePanel.setX( spacePanel.getX() + 1 );
}
}
};
*/
KeyListener moveShip = new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_RIGHT && spacePanel.getX() < 375)
{
spacePanel.setX( spacePanel.getX() + 5 );
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT && spacePanel.getX() > 0)
{
spacePanel.setX( spacePanel.getX() - 5);
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_UP && spacePanel.getY() > 0)
{
spacePanel.setY( spacePanel.getY() - 5);
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN && spacePanel.getY() < 700)
{
spacePanel.setY( spacePanel.getY() + 5 );
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_X)
{
System.out.printf("X: %d, Y: %d\n", spacePanel.getX(),
spacePanel.getY());
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
};
windowFrame.addKeyListener(moveShip);
}
/** ANIMATION LISTENER CLASS **/
public static class AnimationListener implements ActionListener
{
private SpacePanel panel;
private Graphics graphics;
public AnimationListener(SpacePanel panel)
{
this.panel = panel;
this.graphics = panel.getGraphics();
}
#Override
public void actionPerformed(ActionEvent e)
{
panel.repaint();
}
}
/** SPACE PANEL SUBCLASS **/
public class SpacePanel extends JPanel
{
// Variables for the space ship's position temporarily placed here
private int x;
private int y;
// Constructor
public SpacePanel()
{
super();
x = 0;
y = 0;
}
// Getters
public int getX()
{
return x;
}
public int getY()
{
return y;
}
// Setters
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
#Override
public void paint(Graphics g)
{
g.drawImage(spaceBackground, 0, 0, this);
g.drawImage(shipSprite, x, y, this);
}
}
}

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.

Null Pointer Exception on GUI application using three classes

I'm working on a fairly basic game for myself. New to Java Swing but not to Cpp. Onto the problem at hand.
As I start to run the GUI app, I'm shot with a Null Pointer Exception and given four links where they happen(I use Eclipse as my IDE). But when I look at them I see no problem with the lines or anything around them.
So I came to see if any of you can spot what I can't find.
This class grabs the picture from the source folder and sets up the keys for giving movement.
import java.awt.event.KeyEvent;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SPRITES
{
private int x_sped;
private int y_sped;
private int x;
private int y;
private Image sprite;
public SPRITES()
{
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png")); //exception here, line 17
sprite = pine.getImage();
x = 0;
y = 0;
}
public void move()
{
x += x_sped;
y += y_sped;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getImage()
{
return sprite;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = -1;
}
if(key == KeyEvent.VK_D)
{
x_sped = 1;
}
if(key == KeyEvent.VK_W)
{
y_sped = -1;
}
if(key == KeyEvent.VK_S)
{
y_sped = 1;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = 0;
}
if(key == KeyEvent.VK_D)
{
x_sped = 0;
}
if(key == KeyEvent.VK_W)
{
y_sped = 0;
}
if(key == KeyEvent.VK_S)
{
y_sped = 0;
}
}
}
The second one is for getting the frame setting up with completely making the frame and finishing up the making of the movement.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Stage extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private Timer start_stop;
private SPRITES player;
public Stage()
{
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.black);
setDoubleBuffered(true);
player = new SPRITES();
start_stop = new Timer(5, this);
start_stop.start();
}
public void paint(Graphics character)
{
super.paint(character);
Graphics2D G2D = (Graphics2D) character;
G2D.drawImage(player.getImage(), player.getX(), player.getY(), this);
Toolkit.getDefaultToolkit().sync();
character.dispose();
}
public void actionPerformed(ActionEvent arg0)
{
player.move();
repaint();
}
private class TAdapter extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
player.keyReleased(e);
}
public void keyPressed(KeyEvent e)
{
player.keyPressed(e);
}
}
}
This last one should tie it all together...granted I knew how to fix the exception.
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Framing extends JFrame
{
public Framing()
{
add(new Stage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setLocationRelativeTo(null);
setTitle("FLY");
setResizable(false);
setVisible(true);
}
public static void main(String[] args)
{
new Framing();
}
}
What is causing these exceptions to happen? How can I fix the problem and what should I work on to avoid this happening again?
I think you are misreading the stacktrace from eclipse. All the links except for the first(The one at the top) is the call stack, which show the calls made to the place where you got a nullpointer exception.
Which fit because the code:
new Framing()
Calls
add(new Stage())
which calls
player = new SPRITES();
Which calls
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png"));
And this is where your nullpointer exception is. My guess is that getResources("Untitled.png"); returns null which then causes the ImageIcon constructor to throw a nullpointer exception.

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