• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JFrame.getContentPane(Jpanel) null pointer exception

 
Chadd Franck
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain to me why this code throws a null pointer exception at

openFrame.setContentPane(openPanel);
[code}
import javax.swing.*;
import java.awt.event.*;

public class Main {

JFrame openFrame;
JPanel openPanel;

public static void main(String[] args)
{
Main main = new Main();
main.Go();

}

public void Go()
{
openPanel = new JPanel();

openFrame.add(openPanel);
openFrame = new JFrame("MysteryQuest (tm)");
openFrame.setSize(400,600);
openFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);

JMenuItem openMenuItem = new JMenuItem("Open...");

fileMenu.add(openMenuItem);
menuBar.add(fileMenu);

openFrame.setJMenuBar(menuBar);

openFrame.setVisible(true);
}

}
[/code]

Thanks
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you have not yet instantiated the JFrame yet, so the variable openFrame is still null.

Just reverse these two lines:

openFrame.add(openPanel);
openFrame = new JFrame("MysteryQuest (tm)");


(the second one goes first).
 
Chadd Franck
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Egg on my face, I see that, hehe thanks.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49361
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chadd Franck:
Egg on my face, I see that, hehe thanks.


Don't worry about it; everybody makes that sort of mistake.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic