How to Change the Background Color of TopComponents

A recurring question, this time asked by Dieter Bogdoll from Siemens, is how to change the background color of TopComponents. I added this to a TopComponent:

public void paintComponent(Graphics g) {
    Paint p = new GradientPaint(0, 0, Color.BLUE, getWidth(), 0, Color.RED);
    Graphics2D g2d = (Graphics2D) g;
    g2d.fillRect(0, 0, getWidth(), getHeight());

Of course, you don't have to use GradientPaint, but I happen to like it. :-) And then I got the change I expected, i.e., the paintTopComponent (and see what is written about setBackground) can be overridden in each TopComponent, so that you're able to control the background color for each TopComponent:

Hope that answers this question forever!


Thanks for your fast response. But probably I have expressed myself a bit wrong. What I would like is to change the background of the tab of the TopComponent. In my application I have several windows opened, but stacked. You can see tabs of the TopComponents but not necessarily their content. Now if something specific happens in the window I would like to change the color of the tab of the TopComponent. Currently I'm using Icons for that,
but I would like to use the background color for it.

Posted by Dieter Bogdoll on September 30, 2011 at 11:37 PM PDT #

Presumably you would use super.paintComponent(g) at the end - otherwise child components would not be displayed!

Posted by Jesse Glick on October 04, 2011 at 03:02 AM PDT #

Thanks, Geertjan. This did the trick for me.

I just substituted the 'new GradientPaint()' with a fixed java.awt.Color instance and it did the trick.

Posted by Robert Casey on October 07, 2011 at 06:48 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.


« July 2015