NullPointerException when setting a panel layout to null?

pivot5 :

I am attempting to create a GUI where the layout is null so that I can easily create and erase images with pixel dimensions, however I receive a NullPointerException when I try to do so.

According to https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html, simply setting the layout to null should suffice, however when I do it I receive the NullPointerException.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Component;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
import java.util.*;

public class DriverClass extends JFrame {
  /*
   * The frame to contain all GUI.
   */
  public JFrame frame;
  /*
   * The Panel to contain all GUI.
   */
  public JPanel panel;
  /*
   * Class constructor
   */
  public DriverClass () {
   setSize(400,400);
   JPanel panel = new JPanel();
   panel.setSize(400,400);
   panel.setLayout(null); //NullPointerException occurs here
   add(panel);
   setVisible(true);
   panel.setVisible(true);
   frame.pack();
  }
  /*
   * The main method that runs the example class
   */
  public static void main (String[] args) {

    DriverClass driver = new DriverClass();

  }
}

What I expect is a simple working JFrame for me to add images to (through another class) however I am instead prevented from the first step. The error is as follows:

    at TextDriverClass.<init>(TextDriverClass.java:40)
    at TextDriverClass.main(TextDriverClass.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)

The line the first error line points to is indicated in the comments of the code. Please note that I have not created any components or children other than the JPanel so I should not have to worry about using setbounds() or repaint() yet.

Marco R. :

The error is not in the line you are indicating; but in:

frame.pack()

The field frame is null and that's what giving you the NPE. I think you are meaning to invoke:

this.pack()

since your DriverClass already extends JFrame. In such case, you really don't need the public JFrame frame field.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92977&siteId=1