Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Transparency rendering error

I am currently developing a kiosk style Java program to display weather, time, forecast etc. Here is a shot of what the program should look like (screenshot taken before the time updated)

Image showing required output before the graphical error

The various sections are created as JPanels with the paintComponent() method overridden. They draw in a gradient header and a semitransparent background. However, when I change the content of one of these panels, the previous content is left behind, rather than being removed. An example is shown below:

As you can see, when the time changed from 11:51 to 11:52, the numbers overlapped, and the background became lighter (because the semitransparent background was redrawn over it)

The Graphical Error

Image showing the graphical error

What should I do to prevent this overlap? Ultimately, I would prefer to not have to redraw the entire screen when an individual panel updates it's contents. I would prefer to only redraw that particular section. It would be easy to repaint the background, and then all the components within.

Update

Several answers involve clearing the area to be drawn. Whether I use g.clear() or AlphaComposite.CLEAR it erases the background image. this can be seen in the following image. Perhaps if I could copy the background before I clear the area, I could repaint that section of the background, then layer the other images appropriately. Thoughts?

enter image description here

Update 2

An answer was submitted which shows a complete working example of a timer laid over a transparent panel and a background. This is very useful, however, I am not painting my sub-componenets manually. The time, weather icons and temperatures are all JLabels laid out over the semi-transparent panel. I would prefer to not have to paint the individual components manually.

like image 475
Peaches491 Avatar asked Jul 27 '12 16:07

Peaches491


1 Answers

A similar problem

image before

is addressed here

image after

Note also, "Swing programs should override paintComponent() instead of overriding paint()."—Painting in AWT and Swing: The Paint Methods.

like image 168
trashgod Avatar answered Sep 27 '22 17:09

trashgod