Double Tapping Key Press in Java - java

I am making a Java game for my final project. I have my basic class Structure made. I want it to when I press escape it brings up a pause menu and if I press it again then it will exit the program.
This is the code I have so far.
package Pong;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.util.*;
public class Pong implements ActionListener, KeyListener
{
public static Pong pong;
public int width = 1300, height = 750;
public RenderingClass renderer;
int balls;
int gameStart = 0;
public Paddles paddle1, paddle2;
public Ball ball1;
public boolean w, s, up, down;
public int time = 0;
public Pong()
{
JFrame frame = new JFrame("Extreme Pong: Final Game");
Timer timer = new Timer(time, this);
renderer = new RenderingClass();
frame.setSize(width + 15, height);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(this);
frame.add(renderer);
start();
timer.start();
}
public void start()
{
paddle1 = new Paddles(this, 1);
paddle2 = new Paddles(this, 2);
ball1 = new Ball(this, 1);
}
public void update()
{
if(w)
{
paddle1.move(true);
}
if(s)
{
paddle1.move(false);
}
if(up)
{
paddle2.move(true);
}
if(down)
{
paddle2.move(false);
}
}
public void render(Graphics2D page)
{
page.setColor(Color.BLACK);
page.fillRect(0, 0, width, height);
page.setColor(Color.WHITE);
if(gameStart == 0)
{
page.setFont(new Font("3 by 5 Regular", 1, 50));
page.drawString("PONG 2.0", width / 2 - 50, 50);
}
else if(gameStart == 1)
{
page.setFont(new Font("3 by 5 Regular", 1, 50));
page.drawString("GAME PAUSED", width / 2 - 120, height / 2);
}
else if(gameStart == 2)
{
page.setColor(Color.WHITE);
page.setStroke(new BasicStroke(5));
page.drawLine(width / 2, 5, width / 2, height);
page.setFont(new Font("3 by 5 Regular", 1, 100));
page.drawString(Integer.toString(0), width / 3, 75);
page.drawString(Integer.toString(0), width / 3 * 2 - 60, 75);
paddle1.render(page);
paddle2.render(page);
ball1.render(page);
}
}
public void actionPerformed(ActionEvent event)
{
if(gameStart == 2)
{
update();
}
renderer.repaint();
update();
}
public static void main(String[] args)
{
pong = new Pong();
}
public void keyPressed(KeyEvent event)
{
int source = event.getKeyCode();
if(source == KeyEvent.VK_W)
{
w = true;
}
else if(source == KeyEvent.VK_S)
{
s = true;
}
else if(source == KeyEvent.VK_UP)
{
up = true;
}
else if(source == KeyEvent.VK_DOWN)
{
down = true;
}
else if(source == KeyEvent.VK_SPACE)
{
gameStart = 2;
}
else if(source == KeyEvent.VK_ESCAPE) !!!!!!!!!!
{
gameStart = 1;
if(source == KeyEvent.VK_ESCAPE)
{
System.exit(1);
}
}
}
public void keyReleased(KeyEvent event)
{
int source = event.getKeyCode();
if(source == KeyEvent.VK_W)
{
w = false;
}
else if(source == KeyEvent.VK_S)
{
s = false;
}
else if(source == KeyEvent.VK_UP)
{
up = false;
}
else if(source == KeyEvent.VK_DOWN)
{
down = false;
}
}
public void keyTyped(KeyEvent event)
{
}
}
With this code it exits on the first press but I want it to exit on the second press. Thank you.

You may simply use a variable to know if it is the first or second use of
Escape, say
boolean escapeHit = false;
Then just use it
else if(source == KeyEvent.VK_ESCAPE)
{
gameStart = 1;
// second escape key
if(escapeHit){
System.exit(1);
}
else
{
// first escape key
// display pause menu or whatever..
escapeHit = true;
}
}

You're setting your variable to 1 (which I assume brings up the pause menu?) but your second if still passes and thus the program exits.
Try something like this:
public void keyPressed(KeyEvent event)
{
...
else if(source == KeyEvent.VK_ESCAPE)
{
if(gameStart!=1)
{
gameStart = 1;
}
else
{
System.exit(1);
}
}
}

Related

Java KeyListener dissappears when adding new object

Brand new to this forum. Tried to learn Java by tutorials for a while, which have worked fine until now when I'm playing around with Swing making a Pong game..
My problem is that when I try to change level in my game my player's keylistener stops working.
I have tried to remove all unnecessary code, hopefully I haven't missed any that causes confusion.
This is what happens in my Main-class, where Data is basically a JPanel working as my background and Player is Another JPanel, I'll get to the Player-class after main.
public class Main {
Data data = new Data(Color.RED);
Player player = new Player(700, 500, 20, 100);
public Main() throws InterruptedException{
run(data, player);
ballRecursive();
}
public void run(Data data) throws InterruptedException {
frame.add(player, BorderLayout.WEST);
frame.add(data, BorderLayout.CENTER);
}
public void ballRecursive() throws InterruptedException {
if(playerScore.returnScore()==1){
Data data = new Data(Color.GREEN);
run(data);
}
This is my Player, tried to remove anything unnecessary here aswell:
public class Player extends JPanel implements ActionListener, KeyListener{
Timer timer = new Timer(5, this);
double yPos = 0, movementY = 0;
int squareSize = 60;
int yBound;
public Player(int w, int h, int width, int height) {
timer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
yBound = (windowHeight - squareSize);
}
public void actionPerformed(ActionEvent e) {
yPos += movementY;
if (yPos < 0) {
yPos = 0;
} else if (yPos + squareSize > yBound) {
yPos = yBound - squareSize;
}
repaint();
}
public void moveUp()
{
if (yPos == 0)
{
movementY = 0;
}
movementY = -1;
}
public void moveDown()
{
if (yPos == yBound)
{
movementY = 0;
}
movementY = 1;
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
moveUp();
}
if (keyCode == KeyEvent.VK_DOWN) {
moveDown();
}
}
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP)
{
movementY = 0;
}
if (keyCode == KeyEvent.VK_DOWN)
{
movementY = 0;
}

NullPointerException on Graphics setColor() [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting a NullPointer Exception at the following line...
p1.setColor(Color.green);
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.color.ColorSpace;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel implements KeyListener {
public int FRAME_WIDTH = 800, FRAME_HEIGHT = 650;
public Image screen;
//Player 1
public int x = 100;
public int y = 100;
public int px = 117;
public int py = 115;
public boolean up, down, right, left;
public Graphics p1;
//Player 2
public int x2 = 600;
public int y2 = 100;
public int px2 = 617;
public int py2 = 115;
public boolean up2, down2, right2, left2;
public Graphics p2;
public static void main(String[] args) {
JFrame frame = new JFrame("Game");
Main main = new Main();
frame.add(main);
frame.setSize(main.FRAME_WIDTH, main.FRAME_HEIGHT);
frame.setBackground(Color.BLACK);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.screen = frame.createImage(main.FRAME_WIDTH, main.FRAME_HEIGHT);
main.p1 = main.screen.getGraphics();
main.p2 = main.screen.getGraphics();
while(true) {
//Player 1
if(main.up = true) {
main.y+=2;
}
if(main.down = true) {
main.y-=2;
}
if(main.right = true) {
main.x+=2;
}
if(main.left = true) {
main.x-=2;
}
//Player 2
if(main.up2 = true) {
main.y2+=2;
}
if(main.down2 = true) {
main.y2-=2;
}
if(main.right2 = true) {
main.x2+=2;
}
if(main.left2 = true) {
main.x2-=2;
}
frame.repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void paintComponent(Graphics g) {
String player1 = "Player 1";
String player2 = "Player 2";
p1.setColor(Color.green);
p2.setColor(Color.green);
p1.drawString(player1, x, y);
p2.drawString(player2, x2, y2);
p1.setColor(Color.red);
p2.setColor(Color.red);
p1.fillOval(px, py, 5, 5);
p2.fillOval(px2, py2, 5, 5);
g.drawImage(screen, 0, 0, this);
}
#Override
public void keyPressed(KeyEvent e) {
//Player 1
if(e.getKeyCode() == KeyEvent.VK_W) {
up = true;
}
if(e.getKeyCode() == KeyEvent.VK_S) {
down = true;
}
if(e.getKeyCode() == KeyEvent.VK_D) {
right = true;
}
if(e.getKeyCode() == KeyEvent.VK_A) {
left = true;
}
//Player 2
if(e.getKeyCode() == KeyEvent.VK_UP) {
up2 = true;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
down2 = true;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
right2 = true;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
left2 = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
//Player 1 - Release
if(e.getKeyCode() == KeyEvent.VK_W) {
up = false;
}
if(e.getKeyCode() == KeyEvent.VK_S) {
down = false;
}
if(e.getKeyCode() == KeyEvent.VK_D) {
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_A) {
left = false;
}
//Player 2 - Release
if(e.getKeyCode() == KeyEvent.VK_UP) {
up2 = false;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
down2 = false;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
right2 = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
left2 = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Like arynaq said, the Graphics object is never given a value, so you need to initialize that, but for your key listener issue, to resolve this you need to add a key listener to the frame
frame.addKeyListener(this);

paintComponent method won't work - Java

When I use this code my screen will be empty. So that means
something is wrong with my paintComponent method. But what is wrong? And how do I fix it? My expected output was a dark gray rectangle, and an image.
Code:
package _47b3n.seg.main.engine;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import _47b3n.seg.main.frame.Frame;
public class Engine extends JPanel {
public int xOff;
public int yOff;
public int x;
public int y;
public int fpsInt = 199;
public boolean isRunning = true;
public FPS fps = new FPS();
public static void main(String [] args) {
Frame frame = new Frame();
frame.setFrame(800, 600, "Super easy game", "0.0.1");
new Engine();
}
public Engine() {
start();
}
public void move() {
x+=xOff;
y+=yOff;
}
public void start() {
Thread loop = new Thread () {
public void run() {
gameLoop();
addKeyListener(new keyInput());
}
};
loop.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(10, 10, 10, 10);
g.drawImage(new ImageIcon("Poppetje.jpg").getImage(), x, y, null);
}
public void gameLoop() {
while(isRunning) {
move();
repaint();
fps.update();
fpsInt++;
if (fpsInt == 200) {
System.out.println("[Console] " + fps.getFPS() + " FPS");
fpsInt = 0;
}
try {Thread.sleep(17);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public class keyInput extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W) {
yOff = -1;
}
if (key == KeyEvent.VK_S) {
yOff = 1;
}
if (key == KeyEvent.VK_A) {
yOff = -1;
}
if (key == KeyEvent.VK_D) {
xOff = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yOff = 0;
}
if (key == KeyEvent.VK_S) {
yOff = 0;
}
if (key == KeyEvent.VK_A) {
xOff = 0;
}
if (key == KeyEvent.VK_D) {
xOff = 0;
}
}
}
}
Thanks
Don't know if it is the only problem, but you never add the panel to the frame:
//new Engine();
Engine engine = new Engine();
frame.add(engine);
frame.setVisible(true);

Restarting a Thread to restart a game

I am making a multiplayer air hockey game as a project. When the ball falls my game stops and I want to restart the game, to count player scores. My question is how can I restart the game?
My code is:
package proje;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
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;
public class BallGame extends JPanel implements KeyListener, ActionListener,
Runnable {
static boolean right = false;
static boolean left = false;
static boolean right2 = false;
static boolean left2 = false;
int disk2x = 60;
int disk2y = 20;
int disk1x = 60;
int disk1y = 450;
public boolean intersects(Rectangle r, Rectangle p) {
int a;
int b;
int radiusR = (r.width / 2);
int radiusP = (p.width / 2);
double hip;
a = Math.abs((r.x) - (p.x));// x düzleminde yarıçapları farkı
b = Math.abs((r.y)) - ((p.y));// y düzleminde yarıçapları farkı
hip = Math.abs(Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)));
if (hip < radiusR + radiusP) {
return true;
} else
return false;
}
int ballx = 60;
int bally = 43;
Rectangle Ball = new Rectangle(ballx, bally, 20, 20);
Rectangle disk1 = new Rectangle(disk1x, disk1y, 56, 56);
Rectangle disk2 = new Rectangle(disk2x, disk2y, 56, 56);
Thread t;
BallGame() {
addKeyListener(this);
setFocusable(true);
t = new Thread(this);
t.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
BallGame game = new BallGame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setLocationRelativeTo(null);// pencere ortada olsun diye
frame.setResizable(false);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, 500, 600);
g.setColor(Color.green);
g.fillRect(0, 0, 200, 7);
g.setColor(Color.green);
g.fillRect(300, 0, 200, 7);
g.setColor(Color.green);
g.fillRect(0, 566, 200, 7);
g.setColor(Color.green);
g.fillRect(300, 566, 200, 7);
g.setColor(Color.green);
g.fillRect(0, 0, 7, 600);
g.setColor(Color.green);
g.fillRect(489, 0, 7, 600);
g.setColor(Color.red);
g.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
g.setColor(Color.blue);
g.fillOval(disk1.x, disk1.y, disk1.width, disk1.height);
g.setColor(Color.black);
g.fillRect(500, 600, 500, 600);
g.setColor(Color.yellow);
g.fillOval(disk2.x, disk2.y, disk2.width, disk2.height);
}
int movex = -2;
int movey = -2;
boolean BallFall = false;
int count = 0;
public void run() {
while (BallFall == false) {
if (intersects(disk2, Ball)) {
movey = -movey;
}
repaint();
Ball.x += movex;
Ball.y += movey;
if (left2 == true) {
disk2.x -= 3;
right2 = false;
}
if (right2 == true) {
disk2.x += 3;
left2 = false;
}
if (left == true) {
disk1.x -= 3;
right = false;
}
if (right == true) {
disk1.x += 3;
left = false;
}
if (disk1.x <= 4) {
disk1.x = 4;
} else if (disk1.x >= 445) {
disk1.x = 445;
}
if (intersects(Ball, disk1)) {
movey = -movey;
}
if ((200 <= Ball.x) && (Ball.x <= 300) && (Ball.y <= 0)) {
BallFall = true;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 480) {
movex = -movex;
}
if (Ball.y <= 0) {
movey = -movey;
}
if ((Ball.y >= 560) && (Ball.x >= 300)) {
movey = -movey;
}
if ((Ball.y >= 560) && (Ball.x <= 200)) {
movey = -movey;
}
if ((200 <= Ball.x) && (Ball.x <= 300) && (Ball.y >= 600)) {
BallFall = true;
}
try {
Thread.sleep(8);
} catch (Exception ex) {
}
}
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT) {
right = true;
}
if (keyCode == KeyEvent.VK_A) {
left2 = true;
}
if (keyCode == KeyEvent.VK_D) {
right2 = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT) {
right = false;
}
if (keyCode == KeyEvent.VK_A) {
left2 = false;
}
if (keyCode == KeyEvent.VK_D) {
right2 = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void actionPerformed(ActionEvent e) {
}
}

How do I get fluid motion for my program?

The program works fine, but when I hold a key or change keys the motion is not smooth. It pauses for a split second before becoming smooth. I'm still a beginner at Java so please explain in detail.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game2015
{
JFrame frame;
DrawRect mainPanel;
GridBagLayout gridbag;
GridBagConstraints constraints;
Data data;
int width;
int height;
public static void main(String[] args)
{
new Game2015();
}
public Game2015()
{
frame = new JFrame();
width = 400;
height = 500;
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setSize(width, height);
frame.setResizable(false);
data = new Data();
mainPanel = new DrawRect(data);
mainPanel.setFocusable(true);
mainPanel.setBackground(Color.WHITE);
KeyHandler keys = new KeyHandler();
mainPanel.addKeyListener(keys);
frame.add(mainPanel);
frame.validate();
frame.setLocationRelativeTo(null);
Thread thread = new Thread(new Runnable(){
public void run()
{
while(true)
{
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
});
thread.start();
}
public class KeyHandler implements KeyListener
{
public void keyReleased(KeyEvent event)
{
}
public void keyTyped(KeyEvent event)
{
}
public void keyPressed(KeyEvent event)
{
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP)
{
if(data.getY() >= data.getSpeed())
{
data.setY(data.getY() - data.getSpeed());
}
else
{
data.setY(0);
}
}
else if(event.getKeyCode() == KeyEvent.VK_S || event.getKeyCode() == KeyEvent.VK_DOWN)
{
if(data.getY() + 95 <= height - data.getSpeed())
{
data.setY(data.getY() + data.getSpeed());
}
else
{
data.setY(height - 95);
}
}
else if(event.getKeyCode() == KeyEvent.VK_A || event.getKeyCode() == KeyEvent.VK_LEFT)
{
if(data.getX() >= data.getSpeed())
{
data.setX(data.getX() - data.getSpeed());
}
else
{
data.setX(0);
}
}
else if(event.getKeyCode() == KeyEvent.VK_D || event.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(data.getX() + 75 <= width - data.getSpeed())
{
data.setX(data.getX() + data.getSpeed());
}
else
{
data.setX(width - 75);
}
}
else if(event.getKeyCode() == KeyEvent.VK_ESCAPE)
{
frame.dispose();
System.exit(0);
}
}
}
}
The code for drawing the rectangle is this:
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class DrawRect extends JPanel
{
BufferedImage img_player;
File file;
Data data;
public DrawRect(Data newData)
{
data = newData;
try
{
file = new File("Images\\Player.png");
img_player = ImageIO.read(file);
}
catch (Exception exception)
{
}
}
#Override
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.drawImage(img_player, data.getX(), data.getY(), null);
}
}
and the code for the Data class is this:
public class Data
{
int x, y, speed;
public Data()
{
x = 0;
y = 0;
speed = 10;
}
public void setSpeed(int new_speed)
{
speed = new_speed;
}
public int getSpeed()
{
return speed;
}
public void setX(int new_x)
{
x = new_x;
}
public int getX()
{
return x;
}
public void setY(int new_y)
{
y = new_y;
}
public int getY()
{
return y;
}
}
This is because of have java handles events: When you first press a key, it fires an event (pressing the key), and only after a small period of time does it continue to fire events (holding the key). You can test this by printing out every time an event is fired, and it will have a small delay between the first and the rest of the events.
The way to work around this is instead of every time you press a key changing the characters position, change the characters velocity.
For example, instead of
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
if(data.getY() >= data.getSpeed())
{
data.setY(data.getY() - data.getSpeed());
} else {
data.setY(0);
}
} ... etc ...
it would be
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
data.setVelocityY(-data.getSpeed());
} ... etc ...
as well as that, you'd also need to stop their velocity when they release the key. In your keyReleased() method, just do the same thing, but instead of setting velocity to speed, set it to 0.
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
data.setVelocityY(0);
} ... etc ...
and then in your game loop and a method update() that handles calculations (adding velocity to position)
So
public void run() {
while(true) {
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
would be
public void run() {
while(true) {
update();
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
where the update method would be
public static void update() {
data.setY(data.getY() + data.getVelocityY());
data.setX(data.getX() + data.getVelocityX());
}
You should look up basic tutorials on java games. For example, I always found this a good introductory tutorial.

Categories