Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Java Graphics Disappear

Hi all,

I am trying to place some simple graphics on a JFrame window using the Graphics2D class. The graphics rarely remain on the window more than 1/10 of a second. Here is the body of the main method:

JFrame win;
Container contentPane;
Graphics2D g;

win = new JFrame();
win.setSize(300, 200);
win.setLocation(100, 100);
win.setVisible(true);

contentPane = win.getContentPane();

g = (Graphics2D)contentPane.getGraphics();
g.setColor(Color.BLUE);
g.drawRect(50, 50, 100, 30);

g.setColor(Color.RED);
g.fillRect(175, 50, 100, 30);

win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I also tried outputting a line instead of rectangles. I am using the Eclipse IDE; but I have also tried it with the command prompt, which worked correctly maybe half of the time, better than with Eclipse. I've also copied code directly from a textbook, and it did not work.

Thanks a lot.

Davy
[1152 byte] By [DavyGeek] at [2007-11-11 8:38:09]
# 1 Re: Java Graphics Disappear
you should override the JFrames paint method. The way your doing it, the graphics will be lost when a repaint is needed. (move the window, resize the window, etc.)

win = new JFrame(){
public void paint(Graphics g){
g.setColor(Color.BLUE);
g.drawRect(50, 50, 100, 30);

g.setColor(Color.RED);
g.fillRect(175, 50, 100, 30);

}
}

can't remember if it's paint or paintComponent. Actually not even sure if it's right to do the painting on a JFrame...I've always done it with a JPanel.
Joe Beam at 2007-11-11 22:34:49 >
# 2 Re: Java Graphics Disappear
Thanks, Joe. I tried what you said to do, and it works perfectly now (without adding a JPanel). Thanks a lot!

Davy
DavyGeek at 2007-11-11 22:35:43 >