1

I Want to set gradient background color for JToolBar in Java. Am able to set this gradient effect for JPanel.

Thanks, Sathish

oliholz
  • 7,447
  • 2
  • 43
  • 82
Sathish
  • 1,481
  • 5
  • 20
  • 33

1 Answers1

1

Like any other Swing component, you must override its paintComponent(...) method. For instance,

@Override
protected void paintComponent(Graphics g){
    // Create the 2D copy
    Graphics2D g2 = (Graphics2D)g.create();

    // Apply vertical gradient
    g2.setPaint(new GradientPaint(0, 0, Color.WHITE, 0, getHeight(), Color.BLUE));
    g2.fillRect(0, 0, getWidth(), getHeight());

    // Dipose of copy
    g2.dispose();
}

If you want this gradient to show through the components on the JToolBar, you must invoke setOpaque(false) on each of those components.

mre
  • 43,520
  • 33
  • 120
  • 170
  • @Sathish, no problem! I'm just confused by the fact that you said you were able to do this for `JPanel`, but unable to do it for `JToolBar`...:) – mre Jun 21 '11 at 12:11