drawing in a JFrame

In the Paint method of a JFrame I can call a method like drawRect( ) and it will work. But when I try to call a class method for drawing, it won't work. It creates the window but doesn't draw anything in it.It gives a NullPointerException at DrawTest.paint at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source). I find it puzzling that it mentions RepaintManager since it won't even draw for the first time. It also mentions EventDispatchThread.

Here is a simple example. It uses a class, Design, that just uses drawRect and drawOval. An applet can use the Design class and its methods just fine. Why can't the JFrame do the same?

import java.awt.*;

import javax.swing.*;

public class DrawTest extends JFrame {

Design d;

public DrawTest( ) {

super( "Drawing Test" );

setSize(100, 100 );

setVisible( true );

}

public void init( ) {

d = new Design( );

}

public void paint( Graphics g ) {

super.paint( g );

d.draw( g );

}

public static void main( String args[] ) {

DrawTest application = new DrawTest( );

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

} // end of main

} // end of DrawTest

[1257 byte] By [shirleymcka] at [2007-11-27 9:27:58]
# 1
Well, first, you need to call init(). The code you posted doesn't call it. No one else is going to call it for you, a JFrame is not an applet.Second, you shouldn't generally be painting on the JFrame directly, but on the content pane, or something in the content pane.
bsampieria at 2007-7-12 22:31:22 > top of Java-index,Desktop,Core GUI APIs...
# 2
I assume you would call init() from inside main()?Where could I find sample code for how to set up a JFrame and its content pane?
shirleymcka at 2007-7-12 22:31:22 > top of Java-index,Desktop,Core GUI APIs...
# 3

Don't forget to use the "Code Formatting Tags",

see http://forum.java.sun.com/help.jspa?sec=formatting,

so the posted code retains its original formatting.

> Where could I find sample code for how to set up a JFrame and its content pane?

"How to Make Frames":

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html

Read other sections of the tutorial for more complex examples.

> I assume you would call init() from inside main()?

You don't need an init() method. That is an applet convention and doesn't apply in applications.

Also, you don't override the paint() method. That is an old AWT programming technique. If you want to do custom painting you override JComponent or JPanel. The above tutorial also has a section on "Custom Painting".

camickra at 2007-7-12 22:31:22 > top of Java-index,Desktop,Core GUI APIs...