PDA

View Full Version : drawing in a JFrame


shirleymck
07-02-2007, 09:08 PM
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. 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

shirleymck
07-02-2007, 09:19 PM
I forgot to say that this gives a NullPointerException at the 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. (Sorry, I don't think there is a way to copy and paste all the error messages from the Command Prompt window.)

ess
07-03-2007, 12:27 AM
I am not sure if you could draw straight into a JFrame instance....though, I might be wrong.

I think most Java programmers use an instance of the Canvas class to draw on frames.

here is an example

http://www.bluej.org/resources/demos/bouncingball/Canvas.java

Cheers,
Ess

daniel_g
07-03-2007, 10:43 AM
ess is on track there. What you want to paint on, is not the JFrame, but on its contentPane.

This is more or less the way I always do it, by using JPanels:


import javax.swing.JFrame;

class{
main{
//create JFrame
JFrame frame = new JFrame ("A JFrame");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

//create instance of drawing class
//i guess you could do it on init()..
Design d = new Design();

//add contentPane to frame
//add drawings to contentPane
frame.getContentPane().add(d);
frame.pack();
frame.setVisible(true);

}
}



import javax.swing.JPanel;

Design class extends JPanel{
public Design(){ //constructor
//add initial values
...
//set panel color and size
setBackground (Color.gray);
setPreferredSize (new Dimension(600,600));
}

...stuff
public void paint(Graphics g) {
//drawings go here
super.paint(g);
....stuff
}
...stuff
}