Reputation: 2629
I've tried to draw a line using Graphics class and then put it inside JFrame object:
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Window
{
private JFrame frame;
private Graphics g;
public void Window()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(15, 0);
frame.setSize(600, 200);
frame.setVisible(true);
}
public void DrawCross()
{
g.setColor(Color.BLACK);
g.drawLine(300,0, 200, 0);
frame.paint(g);
}
}
...
run:
Exception in thread "main" java.lang.NullPointerException
at Window.DrawCross(Window.java:33)
at Main.main(main.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Where am I wrong and how to fix my mistake? It's impossible to initialise an object of Graphics class that is abstract.
Upvotes: 0
Views: 153
Reputation: 2629
Working code, created basing on JoopEggen and Reimeus answers:
import java.awt.*;
import javax.swing.*;
class Window
{
private JFrame frame;
public Window()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(15, 0);
frame.setSize(600, 200);
frame.setVisible(true);
}
public void drawCoordinateSystem()
{
frame.add( new CoordinateSystem());
}
}
public class CoordinateSystem extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension size = this.getSize();
g.setColor(Color.BLACK);
g.drawLine(0,size.height/2,size.width, size.height/2);
g.drawLine(size.width/2, 0, size.width/2, size.height);
}
}
class Main
{
public static void main(String [] args)
{
Window h = new Window();
h.drawCoordinateSystem();
}
}
Upvotes: 0
Reputation: 159754
The Graphics
object has not been instantiated resulting in the NPE
being thrown.
This approach is just plain wrong. Don't call paint
directly. Also don't do any custom painting on a JFrame
, instead add a sub-class of JComponent
and override paintComponent
. Here you will have a readily instantiated Graphics
object.
Upvotes: 2
Reputation: 109547
The main error is that it should be public Window()
without void
. That is the constructor notation in java. As you called new Window()
you did not call the public void function Window, hence frame remained null. Hence the NullPointerException.
Upvotes: 2