Custom design JScollPane Java Swing

Vincent Roye picture Vincent Roye · Nov 21, 2011 · Viewed 13.6k times · Source

I need to design this scrollbar for all my scrollpanes :

enter image description here

With Java Swing. I am using Netbeans IDE. What is the simplest solution ?

Thank you very much.

Regards

Answer

Ingo Kegel picture Ingo Kegel · Nov 21, 2011

You can customize the look of a Swing component by setting a custom UI. In the case of a scroll pane's scroll bar, you do

scrollPane.getVerticalScrollBar().setUI(new MyScrollBarUI());

where MyScrollBarUI is derived from javax.swing.plaf.basic.BasicScrollBarUI. To do this for all scroll bars (not only in JScrollPane instances), call

UIManager.put("ScrollBarUI", "my.package.MyScrollBarUI");

before you create any Swing components.

In MyScrollBarUI, you override the following methods:

public class MyScrollBarUI extends BasicScrollBarUI {

    @Override
    protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
        // your code
    }

    @Override
    protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
        // your code
    }
}

Your scroll bar is graphically very simple, so it should not be too hard to implement.