Xearta
Xearta

Reputation: 59

Button Layout Issues - JFrame

I want to create an application with a big area of text in the center with a row of 5 buttons on the bottom. Here is my code:

public TheDungeon()
{
  setTitle("InsertGameNameHere");
  setSize(750, 600);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setLayout(new BorderLayout());
  setLocationRelativeTo(null);


  gameScreen = new JLabel();

  add(gameScreen, BorderLayout.CENTER);
  add(buttonPanel, BorderLayout.SOUTH);

  setVisible(true);    

} 

private void buildButtonPanel()
{
  // Create a panel for the buttons.
  buttonPanel = new JPanel();

  // Create the buttons.
  b1 = new JButton("Button 1");
  b2 = new JButton("Button 2");
  b3 = new JButton("Button 3");
  b4 = new JButton("Button 4");
  b5 = new JButton("Button 5");

  // Add the buttons to the button panel.
  buttonPanel.add(b1);
  buttonPanel.add(b2);
  buttonPanel.add(b3);
  buttonPanel.add(b4);
  buttonPanel.add(b5);
}

My application won't even run. It crashes when I attempt to run it. I'm not sure what the issue is. My error if it helps any:

Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1086)
at java.awt.Container.add(Container.java:998)
at javax.swing.JFrame.addImpl(JFrame.java:562)
at java.awt.Container.add(Container.java:966)
at TheDungeon.<init>(TheDungeon.java:38)
at TheDungeon.main(TheDungeon.java:230)

Upvotes: 1

Views: 189

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

This exception:

Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1086)
at java.awt.Container.add(Container.java:998)
at javax.swing.JFrame.addImpl(JFrame.java:562)
at java.awt.Container.add(Container.java:966)
at TheDungeon.<init>(TheDungeon.java:38)
at TheDungeon.main(TheDungeon.java:230)

Means that you're trying to "de-reference" a null variable at line 38 of your TheDungeon class: at TheDungeon.<init>(TheDungeon.java:38).

I'm guessing that this involves the buttonPanel. Do you ever call buildButtonPane() -- I don't see this call anywhere? If you don't the buttonPanel JPanel will be null.

Solution: call the method before using the JPanel. Even better, have the method return a JPanel which you then use.

The lesson to learn from this problem is not the specific solution, but rather how to read the NullPointerException. It will tell you which line is causing the error, and then you can check the variables on that line to see which is null, then trace back into your code and see why.

Upvotes: 2

Related Questions