• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JFrame.getContentPane(Jpanel) null pointer exception

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Egg on my face, I see that, hehe thanks.
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic