Geertjan's Blog

  • September 30, 2011

How to Change the Background Color of TopComponents

Geertjan Wielenga
Product Manager

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!

Join the discussion

Comments ( 4 )
  • Dieter Bogdoll Saturday, October 1, 2011

    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.

  • Geertjan Saturday, October 1, 2011
  • Jesse Glick Tuesday, October 4, 2011

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

  • Robert Casey Friday, October 7, 2011

    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.

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.