Search code examples
javaswinggradientjscrollpaneviewport

How to add a gradient to a JScrollPane's viewport?


I've seen how to add a gradient by having a class extend a component, override the paintComponent method, and then write code to add a gradient and bam there it is.

But I have a JScrollPane with a JTable on the viewport. I'm adding rows and columns as needed, and I want a gradient for the background, until the rows cover it up.

Getting the viewport and setting the color works great: I just want it be a gradient.

scrollPane.getViewport().setBackground(Color.blue);

Any ideas?


Solution

  • Rather than getting the existing viewport, you need to set a custom one. In particular, extend JViewport to draw a gradient in exactly the same manner you would with any other JComponent. Then call setViewport() on your JScrollPane with an instance of your new class as the argument.