0

I have a NPE Exception, while I have all declared objects:

Main class:

package com.company;
import javax.swing.*;
public class Main extends Plansza{
public static final JFrame frame = new JFrame();
public static void main(String[] args) {
    frame.setLocationRelativeTo(null);
    frame.add(areaPanel);
    frame.setVisible(true);
    frame.setBounds(0,0,800,600);
}
}

GUI class:

package com.company;
import javax.swing.*;
import java.awt.*;
public class Plansza {
int[][] area = new int[8][8];
static public JPanel areaPanel;
Figura figura = new Figura();
public Plansza(){
    plansza();
}
public static void plansza(){
    areaPanel = new JPanel(new GridLayout(8,8));
    areaPanel.add(new JButton("PLAY"));
}
}

console log:

Exception in thread "main" java.lang.NullPointerException
at java.desktop/java.awt.Container.addImpl(Container.java:1117)
at java.desktop/java.awt.Container.add(Container.java:1029)
at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:553)
at java.desktop/java.awt.Container.add(Container.java:436)
at com.company.Main.main(Main.java:7)

the at com.company.Main.main(Main.java:7) is : frame.add(areaPanel);

Idk, should I create object panel in Main? I wanted extend main class by Plansza class, for more clearly code. Where is mistake? I'll glad 4 your help, thanks :)

Emil S
  • 29
  • 4
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Rocco May 20 '21 at 12:05
  • `areaPanel` is null, obviously. – user207421 May 20 '21 at 12:23
  • Clearly I have declared `areaPanel` by: `areaPanel = new JPanel(new GridLayout(8,8));` – Emil S May 20 '21 at 12:27
  • That's an initialization, not a decaration, and it runs in the constructor of an object you haven't constructed yet when you call `frame.add(areaPanel)`. Obviously. – user207421 May 20 '21 at 12:28
  • Solved, I've invoked `new Plansza();` into `public static void main(String[] args)`. Thanks – Emil S May 20 '21 at 12:34
  • Then you don't understand your own object model. What you should be instantiating is `Main`. Otherwise why have it? and get rid of all the `static` attributes. – user207421 May 20 '21 at 12:37
  • So, whatever dont extends `Main` class by anyone class, just create new instance yes? – Emil S May 20 '21 at 13:01
  • paste ofcode org/ydvMcF8EvBujmtjXqNhXGs looks better? – Emil S May 20 '21 at 13:05

0 Answers0