NullPointerException on Graphics setColor() [duplicate] - java

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

Related

My Rectangle moves up despite what key I press with key Listener in Java

I am generally a very bad programmer but have been trying to learn game development for a school project. My problem is that I have a draw method that draws a white rectangle and have a key Listener for movement but for some reason it moves upward despite what key I press not just W A S and D.
If you could help with this I would appreciate.
thanks
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
final int screenHeight = 600;
final int screenWidth = 800;
final int playerSize = 48;
int fps = 60;
KeyHandler keyH = new KeyHandler();
Thread gameThread;
//player default position
int playerX = 100;
int playerY = 100;
int playerSpeed = 1;
public GamePanel() {
this.setPreferredSize(new Dimension (screenWidth, screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
this.addKeyListener(keyH);
this.setFocusable(true);
}
public void startGameThread() {
gameThread = new Thread (this);
gameThread.start();
}
public void run() {
double drawInterval = 1000000000/fps; // 0.01666 seconds = 60 times per seconds
double nextDrawTime = System.nanoTime() + drawInterval;
while(gameThread != null) {
System.out.println("this gmae is runing");
// update information such as character positions
// draw the screen with the updated information
update();
repaint();
try {
double remainingTime = nextDrawTime - System.nanoTime();
remainingTime = remainingTime/1000000;
if(remainingTime<0) {
remainingTime = 0;
}
Thread.sleep ((long) remainingTime);
nextDrawTime += drawInterval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void update() {
if(keyH.upPressed ==true) {
playerY = playerY - playerSpeed;
}
else if (keyH.downPressed ==true){
playerY = playerY + playerSpeed;
}
else if (keyH.leftPressed== true){
playerX = playerX - playerSpeed;
}
else if (keyH.rightPressed == true) {
playerX = playerX +playerSpeed;
}
}
public void paintComponent(Graphics g) {
// to draw something
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.white);
g2.fillRect(playerX, playerY, playerSize, playerSize);
g2.dispose();
}
}
package game;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener {
public boolean leftPressed;
public boolean rightPressed;
public boolean upPressed;
public boolean downPressed;
public boolean spacePressed;
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_D);{
rightPressed = true;
}
if(code == KeyEvent.VK_A);{
leftPressed = true;
}
if(code == KeyEvent.VK_W);{
upPressed = true;
}
if(code == KeyEvent.VK_S);{
downPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
int code = e.getExtendedKeyCode();
if(code == KeyEvent.VK_D);{
rightPressed = false;
}
if(code == KeyEvent.VK_A);{
leftPressed = false;
}
if(code == KeyEvent.VK_W);{
upPressed = false;
}
if(code == KeyEvent.VK_S);{
downPressed = false;
}
}
}

2D Pac-Man getting Pac Man to move

I am trying to create a 2D Pac-Man game using Java but I'm having trouble getting the rectangle which will represent the Pac-Man to move. I think that my issue might be somewhere in my keyPressed method in the Game class but I'm not sure. This is what I have in my main class so far.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable,KeyListener {
private static final long serialVersionUID = 1L;
private boolean isRunning = false;
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public static final String TITLE = "Pac-Man";
public Thread thread;
public static Player player;
public Game() {
Dimension dimension = new Dimension(Game.WIDTH,Game.HEIGHT);
setPreferredSize(dimension);
setMinimumSize(dimension);
setMaximumSize(dimension);
addKeyListener(this);
player = new Player(Game.WIDTH/2,Game.HEIGHT/2);
}
public synchronized void start() {
if(isRunning) {
return;
} else {
isRunning = true;
thread = new Thread(this);
thread.start();
}
}
public synchronized void stop() {
if(!isRunning) {
return;
} else {
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void tick() {
player.tick();
}
private void render() {
BufferStrategy bs= getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
player.render(g);
g.dispose();
bs.show();
}
#Override
public void run() {
int fps = 0;
double timer = System.currentTimeMillis();
long lastTime = System.nanoTime();
double targetTicks = 60.0;
double delta = 0;
double ns = 1000000000/targetTicks;
while(isRunning) {
long currentTime = System.nanoTime();
delta += (currentTime - lastTime)/ns;
lastTime = currentTime;
while(delta >= 1) {
tick();
render();
fps++;
delta--;
}
if((System.currentTimeMillis() - timer) >= 1000) {
System.out.println(fps);
fps = 0;
timer += 1000;
}
}
stop();
}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setTitle(Game.TITLE);
frame.add(game);
frame.setResizable(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = true;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = true;
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
player.up = true;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
player.down = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = false;
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
player.up = false;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
player.down = false;
}
}
}
This is what I have in the Player class so far.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Player extends Rectangle{
private static final long serialVersionUID = 1L;
public boolean right;
public boolean left;
public boolean up;
public boolean down;
private int speed = 4;
public Player(int x, int y) {
setBounds(x,y,32,32);
}
public void tick() {
if(right) {
x+=speed;
}
if(left) {
x-=speed;
}
if(up) {
y-=speed;
}
if(down) {
y+=speed;
}
}
public void render(Graphics g) {
g.setColor(Color.yellow);
g.fillRect(x,y,width,height);
}
}

I made it so that the player is facing the mouse direction, but because of that there is a problem

So basically I wanted to create zombies to interact with them later on, but when I drew them I noticed that all of them are turning to the same direction as the player (to mouse) it happened with everything I drew. How do I fix that? (give each zombie it's own position independent from the mouse direction)
Screen.java
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class Screen extends JPanel implements KeyListener, MouseListener, MouseMotionListener {
private Enemy[] enemy;
private Bullet bullet;
private Player player;
boolean collisionBetweenBnZ = false;
private int mX, mY, key;
private List<Bullet> firedBullets = new ArrayList<Bullet>();
public Screen() {
player = new Player(400, 500);
enemy = new Enemy[10];
for (int i = 0; i < enemy.length; i++) {
enemy[i] = new Enemy();
}
setFocusable(true);
addKeyListener(this);
addMouseMotionListener(this);
addMouseListener(this);
this.requestFocusInWindow();
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
//an obstacle for zombies
g.fillRect(0, 400, 800, 4);
//drawing each bullet as soon as they are added to the list (when pressing mouse button)
for (int i = 0; i < firedBullets.size(); i++) {
firedBullets.get(i).drawBullet(g);
}
//drawing sprites
player.drawPlayer(g);
for (int i = 0; i < enemy.length; i++) {
enemy[i].drawEnemy(g);
}
}
public static int clamp(int num, int min, int max) { //method that prevents you from going beyond the window
if (num >= max) return num = max;
else if (num <= min) return num = min;
else return num;
}
public void fire() {
bullet = new Bullet(player.playerX(), player.playerY());
bullet.updateAngle(mX, mY, player.playerX(), player.playerY());
firedBullets.add(bullet);
}
public void animate() {
while (true) {
try {
Thread.sleep(10); //in milliseconds
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
player.tick();
/*for (int i = 0; i < )
enemy.tick();*/
//System.out.println("X: " + mX + "\n" + "Y: " + mY);
for (int i = 0; i < firedBullets.size(); i++) {
firedBullets.get(i).launch();
}
//if () getbounds
repaint();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
player.setVelX(-2);
}
else if (key == KeyEvent.VK_D) {
player.setVelX(2);
}
else if (key == KeyEvent.VK_S) {
player.setVelY(2);
}
else if (key == KeyEvent.VK_W) {
player.setVelY(-2);
}
else if (key == KeyEvent.VK_SPACE) {
//bullet.shootBullet = true;
}
else if (key == KeyEvent.VK_A && key == KeyEvent.VK_D) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_W && key == KeyEvent.VK_S) {
player.setVelY(0);
}
}
public void keyReleased(KeyEvent e) {
key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_D) {
player.setVelX(0);
}
else if (key == KeyEvent.VK_S) {
player.setVelY(0);
}
else if (key == KeyEvent.VK_W) {
player.setVelY(0);
}
else if (key == KeyEvent.VK_SPACE) {
//bullet.shootBullet = false;
}
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
mX = e.getX();
mY = e.getY();
player.updateAngle(mX, mY);
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
fire();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Enemy.java
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.concurrent.ThreadLocalRandom;
public class Enemy {
private int health, width, height;
private int enemyX, enemyY, velY;
private BufferedImage img;
public Enemy() {
try {
img = ImageIO.read(new File("/Users/david/Desktop/Enemy_Sprite.png"));
} catch (IOException e) {
e.printStackTrace();
}
health = 100;
width = img.getWidth();
height = img.getHeight();
enemyX = ThreadLocalRandom.current().nextInt(50, 750);
enemyY = ThreadLocalRandom.current().nextInt(0, 200);
}
public Rectangle getBounds() {
return new Rectangle(enemyX, enemyY, width, height);
}
public void setVelY(int y) {
velY = y;
}
public void tick() {
enemyY += velY;
}
public boolean obstacleInteraction() {
//if (getBounds() == )
return true;
}
public void drawEnemy(Graphics g) {
g.drawImage(img, enemyX, enemyY, null);
}
}
I figured it out thanks to this person. So basically at the end of my code where I draw player and make him rotate to the mouse position put the saved original plane position
g.setTransform(oldAT);

Double Tapping Key Press in 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);
}
}
}

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

Categories