Line2D, getting NullPointerException
Heya I'm attempting to draw a line using Line2D and Point2D
Here's the problem part of my code:
Code:
public void paint(Graphics g){
Graphics2D ga = (Graphics2D)g;
System.out.println(point1.getX()+ " " + point1.getY());
System.out.println(point2.getX()+ " " + point2.getY());
Line2D line1 = new Line2D.Double(point1, point2);
System.out.println(line1.getX1() + " " + line1.getY1() + " " + line1.getX2() + " " + line1.getY2());
ga.draw(line1);
}
And I get this output:
100.0 100.0
150.0 150.0
Exception in thread "main" java.lang.NullPointerException
100.0 100.0 150.0 150.0
at test.myClass.paint(myClass.java:65)
at test.Main.main(Main.java:35)[/CODE]
I put the print lines to test that the line has all 4 points stored in it before attempting to draw it, yet I keep getting a NullPointerException.
Re: Line2D, getting NullPointerException
which line is line 65?
Quote:
Originally Posted by MonkeyMan
Exception in thread "main" java.lang.NullPointerException
at test.myClass.paint(myClass.java:65)
Re: Line2D, getting NullPointerException
Line 12, the one trying to do the drawing.
Re: Line2D, getting NullPointerException
I think your problem is that the Graphics object being passed into the paint method is null, if you call this method just with 'repaint();' it should work.
To check if this is the problem simply add 'if (g == null)System.out.print("Graphics object Null");'
EDIT: Actually I'm pretty sure you have to do this: super.paint(g); before you use it to initialise 'ga'
Re: Line2D, getting NullPointerException
1. Never use getGraphics() of a Component. Not until you have a very good uncerstainding of AWT and Swing, anyhow.
2. Never call paint() in code. As Borkpaladin has hinted, the correct way to get a painting method to run is to call repaint().
3. For Swing components, the method to override is paintComponent(...), not paint(...).
Recommended reading: Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)
db