14

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

Vincent Roye
  • 2,751
  • 7
  • 33
  • 53
  • i did not get you. a scrollpane automatically inserts a scroll bar when size of element it contains is compromised. – gprathour Nov 21 '11 at 07:35

3 Answers3

20

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.

Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
  • Be sure to override `protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds)` and `paintThumb` (same method signature) in [BasicScrollBarUI](http://docs.oracle.com/javase/6/docs/api/javax/swing/plaf/basic/BasicScrollBarUI.html) or you might not see anything. – Nateowami Dec 20 '15 at 11:28
  • Would it be possible not to hardcode `extends BasicScrollBarUI` but to extend the scrollbar UI class that is currently used? Like `extends scrollBar.getUI().getClass()`? – Bowi Nov 09 '16 at 08:25
  • No that is not possible with inheritance on the JVM – Ingo Kegel Nov 09 '16 at 12:59
1

Don't forget that if you plan to use the UIManager to override all scrollbars like this

UIManager.put("ScrollBarUI", "my.custom.SimpleScrollBarUI");

then your SimpleScrollBarUI class must have the createUI method, i.e:

public class SimpleScrollBarUI extends BasicScrollBarUI {

    public static ComponentUI createUI(JComponent c) {
        return new SimpleScrollBarUI();
    }

    //...

}
1

1) override JToolBar

2) most of Custom Look and Feel overrode that

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    the relation of toolbar to scrollbar is that ... ;-) Plus (after all it's Monday morning): you override methods, classes are extended (or implemented) – kleopatra Nov 21 '11 at 08:55