Keilly: Creating a Swing Dashboard Widget - Part 2 (Border)

Thursday, May 29, 2008

Creating a Swing Dashboard Widget - Part 2 (Border)

Widgets have nice rounded borders. The LineBorder in the JDK doesn't really cut it: It's not anti-aliased, it draws weird artifacts, and it's tough to have the outside of the border transparent while inside the border is opaque.
While there are separate ways to fix these things, it's fairly easy to write one:



As this border does the job of filling the entire background of the component with the component's background color, we can make the actual component transparent and this will leave nice transparent areas outside the curves of the corners. (Opaque components fill their entire bounds with the background color).
The drawback of this is that the border is painted after the component's contents, so custom painting for the widget content must be done in the paint method rather than the paintComponent or it won't show up.

2 comments:

Anonymous said...

Keilly:

Thanks for sharing with us your idea.

I am trying to get rounded borders for a JPanel in one of the projects I am working on. I am not able to get it to work. Could you please give me an example how I could use your class to do this?

You could email me at inayat_jilani@yahoo.com

Thank You.

- Inayat

Neil Cochrane said...

Make sure you do this:

yourPanel.setOpaque(false);

...as if you don't the whole bounds of the component will automatically be filled in the background colour by the Swing painting system.

If you have done that then try and subclass your panel and add a new paintComponent() method to draw a few shapes. This should help you get the hang of things without using the code here. Once you have done that then you should be able to move forward and draw a large rounded rectangle at the back of your component.