This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Have it before you use it...
Posted by Kishori Sharan on May 28, 2001 at 1:31 PM
Hello There is a problem with your program. In constructor of abc frame you are making a call to getGraphics(). Since at that time the frame is not shown, that is, show () method has not been called there is not graphics object attached to it and that is why you are getting NullPOinterException. So, first call show() method on JFrame and then getContentPane and then getGraphics and then draw the line you want to. You need to call update(Graphics) on your container else your line will appear and disappear quickly. WHY??? I have atttached modified version of your program which draws a line on contentpane of JFrame. Thanks Kishori /////////// Abc.java import javax.swing.* ; import java.awt.* ; class Abc extends JFrame{ Abc(){ super() ; setBounds ( 20, 20 , 300, 300 ) ; } public static void main(String args[]){ JFrame f = new Abc() ; f.show ( ) ; Container cp = f.getContentPane ( ) ; Graphics g = cp.getGraphics ( ); // It is importtant to call cp.update(g). Why? // Otherwise, your line will show up and then disappear immediately. cp.update ( g ) ; g.drawLine ( 10, 10, 110, 110 ); } }
Replies:
|