aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes JFrame.getContentPane(Jpanel) null pointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JFrame.getContentPane(Jpanel) null pointer exception" Watch "JFrame.getContentPane(Jpanel) null pointer exception" New topic
Author

JFrame.getContentPane(Jpanel) null pointer exception

Chadd Franck
Ranch Hand

Joined: Nov 05, 2008
Posts: 50
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

Joined: Feb 20, 2001
Posts: 3695

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

Joined: Nov 05, 2008
Posts: 50
Egg on my face, I see that, hehe thanks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JFrame.getContentPane(Jpanel) null pointer exception
 
Similar Threads
Why is this code taking too long to launch
slight problem using JScrollPane
ActionListener Problems
coding a texteditor: want to open a separate option window
Resize problem with JMenuBar