import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
NPE creates my frame
class NPE {
private static Values m_Val;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new Draw(m_Val));
frame.setSize(400,400);
frame.setVisible(true);
}
}
The Draw class paints my Ellipse (should paint)
class Draw extends JPanel{
private Values m_Val;
Draw(Values val){
m_Val = val;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Ellipse2D myOval = new Ellipse2D.Double(m_Val.OVAL_X, m_Val.OVAL_Y,
m_Val.OVAL_W, m_Val.OVAL_H);
Color c = Color.red;
g2.setColor(c);
g2.fill(myOval);
}
}
The Values class provides the x,y,widht,height of the ellipse.
class Values{
int OVAL_X = new Random().nextInt(100);
int OVAL_Y = new Random().nextInt(100);
int OVAL_W = 100;
int OVAL_H = 100;
}
I want to draw an Ellipse by getting its x,y,widht,height from the another class Values
. I read many posts and questions about NPE but I can not manage to solve why m_Val
is null here. Any ideas?
Exception trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot read field "OVAL_X" because "this.m_Val" is null
at questions.Draw.paintComponent(NPE.java:31)