Results 1 to 10 of 10
  1. #1
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Question JMenuBar not working, gives NullPointException

    I've been working on making a small little simulation for my physics class of a space ship in the middle of space. I created the space ship part and all the physics, however, when I tried adding a JMenuBar and all its components (JMenu's and JMenuItem's), it compiles fine, I just get a big huge error when I run it:

    Java Code:
    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    	at spaceshipsim.SpaceShipSim.paint(SpaceShipSim.java:82)
    	at javax.swing.RepaintManager$3.run(RepaintManager.java:819)
    	at javax.swing.RepaintManager$3.run(RepaintManager.java:796)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:108)
    	at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
    	at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:765)
    	at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:707)
    	at javax.swing.RepaintManager.access$1000(RepaintManager.java:62)
    	at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1622)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:226)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:673)
    	at java.awt.EventQueue.access$300(EventQueue.java:96)
    	at java.awt.EventQueue$2.run(EventQueue.java:634)
    	at java.awt.EventQueue$2.run(EventQueue.java:632)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:108)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:643)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
    This error is given when I run the program. The rest of the code still works, that is, the simulation still appears, but the menu bar doesn't.

    Here's the code for the main class:
    Java Code:
    package spaceshipsim;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.util.*;
    
    import spaceshipsim.entities.*;
    
    /**
     * @author Nicolás A. Ortega
     * @copyright Nicolás A. Ortega
     * @license GNU GPLv3
     * @year 2014
     * 
     */
    public class SpaceShipSim extends JFrame implements Runnable, KeyListener {
    	private final String version = "v0.2";
    
    	// Menu items
    	JMenuBar menuBar;
    	JMenu simulationMenu;
    	JMenuItem exitMenuItem;
    
    	// Graphics/Framework items
    	private Thread gameloop;
    	private BufferedImage backbuffer;
    	private Graphics2D g2d;
    	private AffineTransform identity = new AffineTransform();
    
    	// The Ship
    	private Ship ship;
    
    	// Constructor:
    	public SpaceShipSim() {
    		super("Space Ship Simulator");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLayout(new BorderLayout());
    		menuSetup();
    		setSize(800, 600);
    		setVisible(true);
    
    		backbuffer = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
    		g2d = backbuffer.createGraphics();
    
    		ship = new Ship(400, 300);
    		addKeyListener(this);
    
    		start();
    	}
    
    	public void menuSetup() {
    		menuBar = new JMenuBar();
    
    		simulationMenu = new JMenu("Simulation");
    		menuBar.add(simulationMenu);
    
    		exitMenuItem = new JMenuItem("Exit");
    		exitMenuItem.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent ae) {
    				stop();
    				System.exit(0);
    			}
    		});
    
    		this.setJMenuBar(menuBar);
    
    		pack();
    	}
    
    	public void start() {
    		gameloop = new Thread(this);
    		gameloop.start();
    	}
    
    	public void stop() { gameloop = null; }
    
    	public void paint(Graphics g) {
    		g2d.setTransform(identity);
    		g2d.setPaint(Color.BLACK);
    		g2d.fillRect(0, 0, getSize().width, getSize().height);
    
    		drawInfo();
    		drawShip();
    
    		g.drawImage(backbuffer, 0, 0, this);
    	}
    
    	private void drawInfo() {
    		g2d.setPaint(Color.WHITE);
    		g2d.drawString("Welcome to SpaceShipSim " + version, 10, 40);
    		g2d.drawString("Position: " + (int)ship.getX() + ", " + (int)ship.getY(), 10, 55);
    		g2d.drawString("Velocity (px/s): " + (int)(ship.getVelX() * 50) + ", " + (int)(ship.getVelY() * 50), 10, 70);
    		g2d.drawString("Acceleration (px/s/s): " + (int)(ship.getAccelX() * Math.pow(50, 2)) + ", " + (int)(ship.getAccelY() * Math.pow(50, 2)), 10, 85);
    		g2d.drawString("Move Angle: " + (int)ship.getMoveAngle(), 10, 100);
    		g2d.drawString("Face Angle: " + (int)(ship.getFaceAngle() - 90), 10, 115);
    	}
    
    	private void drawShip() {
    		g2d.setTransform(identity);
    		g2d.translate(ship.getX(), ship.getY());
    		g2d.rotate(Math.toRadians(ship.getFaceAngle()));
    		g2d.setColor(Color.RED);
    		g2d.fill(ship.getShape());
    	}
    
    	public void run() {
    		Thread t = Thread.currentThread();
    
    		while(t == gameloop) {
    			try {
    				ship.update();
    
    				Thread.sleep(20);
    			} catch(InterruptedException ie) {
    				ie.printStackTrace();
    			}
    
    			repaint();
    		}
    	}
    
    	public void keyPressed(KeyEvent ke) {
    		//keys[ke.getKeyCode()] = true;
    		int keyCode = ke.getKeyCode();
    
    		if(keyCode == KeyEvent.VK_UP) { ship.setAccelerate(true); }
    		if(keyCode == KeyEvent.VK_LEFT) { ship.setTurnLeft(true); }
    		if(keyCode == KeyEvent.VK_RIGHT) { ship.setTurnRight(true); }
    	}
    	public void keyReleased(KeyEvent ke) {
    		int keyCode = ke.getKeyCode();
    
    		if(keyCode == KeyEvent.VK_UP) { ship.setAccelerate(false); }
    		if(keyCode == KeyEvent.VK_LEFT) { ship.setTurnLeft(false); }
    		if(keyCode == KeyEvent.VK_RIGHT) { ship.setTurnRight(false); }
    	}
    	public void keyTyped(KeyEvent ke) {}
    
    	public static void main(String[] args) { new SpaceShipSim(); }
    }
    I think this might have to do with the way I'm painting it, or adding it to the JFrame, but I don't know.

    Thanks in advance!

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: JMenuBar not working, gives NullPointException

    What line is the error on? What are the values of every variable on that line? Use a debugger or add some print statements to answer that question.

    When you know which variable is null, you'll then be able to track down *why* it's null.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: JMenuBar not working, gives NullPointException

    You use g2d without initializing it. You just added it as a field in your class which is really wired.

    You get a graphics object as parameter and all you need to do is casting it to a Graphics2D:
    Graphics2D g2d = (Graphics2D) g;

    Konrad

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: JMenuBar not working, gives NullPointException

    Quote Originally Posted by kneitzel View Post
    You use g2d without initializing it. You just added it as a field in your class which is really wired.

    You get a graphics object as parameter and all you need to do is casting it to a Graphics2D:
    Graphics2D g2d = (Graphics2D) g;
    It's a little more complicated than that. The g2d variable is actually from a BufferedImage, and it's initialized in the constructor:

    backbuffer = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
    g2d = backbuffer.createGraphics();

    OP needs to find the values of each variable on that line and let us know what's going on before we can proceed.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Default Re: JMenuBar not working, gives NullPointException

    The line mentioned in the error is the paint(Graphics g) function, which is why I was so confused. As for how I used the Graphics2D, I'm not really sure if I'm doing it right or not, it's how I learned to do it (from a Java SE game programming book), could be a bad habit.

    In any case, I managed to get rid of the NullPointException error. I made a quit program that all it did was to have a menu with a quit button, got that to work, and then applied it to this code. First, I moved the setSize(width, height) function to before the menuSetup() function (which is most likely where the problem originated), and then I moved all the "add" functions from the JMenu and JMenuBar variables towards the bottom of the menuSetup() function.

    However, although I don't get the error anymore when running, it still doesn't show the bar at the top of the program. My guess (most likely misguided) is that I need to place something in the paint() function so that it repaints. Or, it could have to do with what kneitzel pointed out about how I use the Graphics2D variable (which is more likely to be the problem).

    There's not much I have to go on for this, I don't get any errors, nor when compiling, nor when running.

    Here's the updated bit of the code:
    Java Code:
    public SpaceShipSim() {
    		super("Space Ship Simulator");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(800, 600);
    		menuSetup();
    		setVisible(true);
    
    		backbuffer = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
    		g2d = backbuffer.createGraphics();
    
    		ship = new Ship(400, 300);
    		addKeyListener(this);
    
    		start();
    	}
    
    	public void menuSetup() {
    		menuBar = new JMenuBar();
    		simulationMenu = new JMenu("Simulation");
    		exitMenuItem = new JMenuItem("Exit");
    
    		exitMenuItem.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent ae) {
    				stop();
    				System.exit(0);
    			}
    		});
    		menuBar.add(simulationMenu);
    		this.setJMenuBar(menuBar);
    	}

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,651
    Rep Power
    5

    Default Re: JMenuBar not working, gives NullPointException

    And don't extend JFrame. Extend JPanel and add it to a JFrame. And then override paintComponent(), not paint(). And don't forget to do super.paintComponent(g) as your first line in paintComponent. I suggest you read about custom painting here ->Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: JMenuBar not working, gives NullPointException

    Kevin was correct: you initialized the g2d variable. I am just used to not have a graphics instance open all the time. So I open it, use it and then close it directly.

    And the paint method should just paint the window. But you also draw something into the image. That is not really wrong but might not be the place to do it. Thos is just some idea to get the code cleaner (where you have to decide if you agree or not. It is your code and you thought something when you wrote it.

    When I made a game, i did this (might not be a good solution. I am not a game developer but it worked for me):
    - I had 3 images that I used. One was the current picture, one was paint and one was reserve.
    - Images was swapped in synchronized methods.
    - one thread was just painting pictures all the time. Once finished, the drawn picture was swaped with the reserved one, a flag was set (new picture available) and a paint was triggeted.
    - when painting, the flag was checked. Was it set, them the picture drawn was swapped with the reserve one. And then the picture was drawn to the screen.
    That way my game logic was independend to the displaYy logic.

    But importsnt: that might be interesting ideas but they do not explain the error right now.

    But i thunk i see the problem now. You set the windows visible which triggers the paint? And them you initialize g2d. Just move the setVisible code below the initialisation of everything.

    Konrad

  8. #8
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Default Re: JMenuBar not working, gives NullPointException

    Alright, I took a look at the lesson that jim gave me (thanks for that!), and now all the graphics are working fine. What I did was to have a main class with a JFrame variable and a another class that extended JPanel. I moved everything except the menus to the new panel class, however, in the process (and I'm going a little off topic based on the title of this thread) now the KeyListener doesn't work. Is the KeyListener not supposed to be in a JPanel class? Because that's where it is, and that's about the only thing that changed for it while I was moving stuff to the JPanel class.

    Just in case, here's the code for my JPanel class:
    Java Code:
    package spaceshipsim;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    
    import spaceshipsim.entities.*;
    
    /**
     * @author Nicolás A. Ortega
     * @copyright Nicolás A. Ortega
     * @license GNU GPLv3
     * @year 2014
     * 
     */
    public class SimPanel extends JPanel implements Runnable, KeyListener {
    	// Graphics/Framework items
    	private Thread gameloop;
    	//private BufferedImage backbuffer;
    	private Graphics2D g2d;
    	//private AffineTransform identity = new AffineTransform();
    
    	// The Ship
    	private Ship ship;
    
    	public SimPanel() {
    		ship = new Ship(400, 300);
    		addKeyListener(this);
    		start();
    	}
    
    	public void start() {
    		gameloop = new Thread(this);
    		gameloop.start();
    	}
    
    	public void stop() { gameloop = null; }
    
    	public void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		g2d = (Graphics2D) g;
    
    		g2d.setColor(Color.BLACK);
    		g2d.fillRect(0, 0, 800, 600);
    
    		drawInfo();
    		drawShip();
    	}
    
    	private void drawInfo() {
    		g2d.translate(0, 10);
    		g2d.setColor(Color.WHITE);
    		g2d.drawString("Welcome to SpaceShipSim v0.2", 10, 10);
    		g2d.drawString("Position: " + (int)ship.getX() + ", " + (int)ship.getY(), 10, 25);
    		g2d.drawString("Velocity (px/s): " + (int)(ship.getVelX() * 50) + ", " + (int)(ship.getVelY() * 50), 10, 40);
    		g2d.drawString("Acceleration (px/s/s): " + (int)(ship.getAccelX() * Math.pow(50, 2)) + ", " + (int)(ship.getAccelY() * Math.pow(50, 2)), 10, 55);
    		g2d.drawString("Move Angle: " + (int)ship.getMoveAngle(), 10, 70);
    		g2d.drawString("Face Angle: " + (int)(ship.getFaceAngle() - 90), 10, 85);
    	}
    
    	private void drawShip() {
    		g2d.translate(ship.getX(), ship.getY());
    		g2d.rotate(Math.toRadians(ship.getFaceAngle()));
    		g2d.setColor(Color.RED);
    		g2d.fill(ship.getShape());
    	}
    
    	public void run() {
    		Thread t = Thread.currentThread();
    
    		while(t == gameloop) {
    			try {
    				ship.update();
    
    				Thread.sleep(20);
    			} catch(InterruptedException ie) {
    				ie.printStackTrace();
    			}
    
    			repaint();
    		}
    	}
    
    	public void keyPressed(KeyEvent ke) {
    		int keyCode = ke.getKeyCode();
    
    		if(keyCode == KeyEvent.VK_UP) { ship.setAccelerate(true); }
    		if(keyCode == KeyEvent.VK_LEFT) { ship.setTurnLeft(true); }
    		if(keyCode == KeyEvent.VK_RIGHT) { ship.setTurnRight(true); }
    	}
    	public void keyReleased(KeyEvent ke) {
    		int keyCode = ke.getKeyCode();
    
    		if(keyCode == KeyEvent.VK_UP) { ship.setAccelerate(false); }
    		if(keyCode == KeyEvent.VK_LEFT) { ship.setTurnLeft(false); }
    		if(keyCode == KeyEvent.VK_RIGHT) { ship.setTurnRight(false); }
    	}
    	public void keyTyped(KeyEvent ke) {}
    }
    Sorry for posting the whole code, I'm in a bit of a hurry to go to the grocery store right now :D

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,651
    Rep Power
    5

    Default Re: JMenuBar not working, gives NullPointException

    Quote Originally Posted by Vampire5 View Post
    now the KeyListener doesn't work. Is the KeyListener not supposed to be in a JPanel class? Because that's where it is, and that's about the only thing that changed for it while I was moving stuff to the JPanel class.
    You can have a keyListener in any panel. It may be a focus issue. Try doing a setFocusable(true) in your JPanel. If that doesn't work, we'll still be here (or someone will).

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Default Re: JMenuBar not working, gives NullPointException

    Yup, jim was right, it was the focus. Everything's alright now!

    Thanks guys!

Similar Threads

  1. NullPointException
    By gyijhbk in forum New To Java
    Replies: 7
    Last Post: 06-28-2012, 01:39 PM
  2. Properties: NullPointException
    By mickylad in forum Advanced Java
    Replies: 2
    Last Post: 11-12-2011, 04:57 PM
  3. JMenuBar error
    By Tastosis in forum New To Java
    Replies: 6
    Last Post: 03-02-2011, 11:55 AM
  4. JMenuBar and Popups
    By snoopygee in forum AWT / Swing
    Replies: 2
    Last Post: 12-10-2010, 10:07 AM
  5. Mutliple JMenuBar
    By chyrl in forum AWT / Swing
    Replies: 10
    Last Post: 11-04-2010, 05:43 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •