help - draw objects doesn't appear on JFrame

i got this code from a book...

import javax.swing.*;

import java.awt.*;

class Ch5SampleGraphics {

public static void main( String[] args ) {

JFramewin;

Container contentPane;

Graphics g;

win = new JFrame("My First Rectangle");

win.setSize(300, 200);

win.setLocation(100,100);

win.setVisible(true);

contentPane = win.getContentPane();

g = contentPane.getGraphics();

g.drawRect(50,50,100,30);

}

}

the problem is when i run the app, the frame doesn't always show the rect drawn. sometimes it shows it, but usualy not. if it does show the rect, once i click on minimize, then reopen it from the taskbar, the rect will disappear again and will never show up.

can anyone help me? i've been searching for answers but to no avail. thanks 4 reading, hope someone will offer some help.

[892 byte] By [santhraxa] at [2007-10-3 3:46:16]
# 1

Ok, two major things here.

1. You're creating components outside of the event dispatch thread (EDT)

2. You're not using the correct paint techniques

Back to square one - read the Java tutorial, specifically the sections on "Swing and threading" and "how to implement custom painting" (they should be fairly easy to find).

itchyscratchya at 2007-7-14 21:42:56 > top of Java-index,Desktop,Core GUI APIs...
# 2
Oh and, hell, I only just spotted this!i got this code from a book...Unless that was included under the title "How not to write Swing code," throw the book away! That code is just so wrong it hurts.What book is it?
itchyscratchya at 2007-7-14 21:42:56 > top of Java-index,Desktop,Core GUI APIs...
# 3
hm.. i'll hv a look at those stuff u said.the book is,an intoduction to oop with java 4th ed.c. thomas wu
santhraxa at 2007-7-14 21:42:56 > top of Java-index,Desktop,Core GUI APIs...
# 4

an intoduction to oop with java

Jesus wept. The code's about as un-object-oriented as you could possibly make it.

Looking at his sample chapter on the book's web page all I see is main() methods with linear code in and just simple number crunching with primitive types. No objects to speak of at all.

I'm sticking with my "throw the book away" advice :o)

itchyscratchya at 2007-7-14 21:42:56 > top of Java-index,Desktop,Core GUI APIs...