This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Swing / AWT / SWT and the fly likes paint()ing a panel Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "paint()ing a panel" Watch "paint()ing a panel" New topic

paint()ing a panel

Dan Howard
Ranch Hand

Joined: Feb 22, 2004
Posts: 47
Very newbie question - sorry,

I'm writing a simple app which draws a maze on a panel. My main class extends a frame and I create the panel. Works fine.

I draw the maze on the panel. I have a drawPanel object where I get the Graphics from (Graphics g = this.drawPanel.getGraphics() Works fine.

Let's say that this window gets covered by another window. When I bring my app back to focus nothing gets repainted.

Is there an example of how I should use the paint method in this case?

Should I draw everything to an Image object and then redraw that image buffer? How does that work?

I think my approach is totally wrong.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24183

Hi Dan,

Welcome to JavaRanch!

Short answer: yes, your approach is totally wrong. Don't use getGraphics() -- instead, implement a method such that a Graphics is just handed to you at exactly the right time. If you're using a java.awt.Panel, then override paint(). If you're using a javax.swing.JPanel, then override paintComponent().

I'm going to move this to the Swing/AWT forum for followup; I'll see you over there. If you don't understand what I mean about overriding, just say so and I'll larn ya.

[Jess in Action][AskingGoodQuestions]
Dan Howard
Ranch Hand

Joined: Feb 22, 2004
Posts: 47
Hi Ernest,

Thanks for the quick reply (I knew my aproach was wrong )

I re-arranged my code so that I create the 2d array of objects and only perform the drawing in an overridden paint method of the Panel.

Works great now, Thanks!
It is sorta covered in the JavaRanch Style Guide.
subject: paint()ing a panel