How to set UI for all Components of a type in java

2019-04-29 14:47发布

I created my own MyScrollbarUI class to have a custom scrollbar look in my application. Now I have to do

scrollPane.getHorizontalScrollBar().setUI(new MyScrollbarUI());
scrollPane.getVerticalScrollBar().setUI(new MyScrollbarUI());

on any ScrollPane I use.

Is it somehow possible to tell Swing that it should use MyScrollbarUI on any scrollbar. Maybe via the UIManager?

4条回答
聊天终结者
2楼-- · 2019-04-29 15:03

Try putting your custom UI class as ScrollPaneUI property of UIManager. By default it is javax.swing.plaf.metal.MetalScrollPaneUI change it to your custom class.

查看更多
Summer. ? 凉城
3楼-- · 2019-04-29 15:15

Make new ScrollPane component by extending JScrollPane and tell your custom ScrollPane to use MyScrollbarUI. Then modify all your code to use your custom ScrollPane instead of JScrollPane.

查看更多
等我变得足够好
4楼-- · 2019-04-29 15:18
UIManager.put("ScrollBarUI", MyScrollbarUI.class.getName());

should do the trick.

You need to have a public static ComponentUI createUI(JComponent c) method in your UI class, returning an instance of your UI.

查看更多
叛逆
5楼-- · 2019-04-29 15:18

technically, it's as easy as to tell the UIManager which delegate to use (as @Harry Joy already mentioned), like

 UIManager.put("ScrollBarUI", "fully-qualified-className-of-customUI") 

This will effectively install the same delegate class for all LAFs which might result less than optimal visuals in all except the one you extended your custom ui-class from. Strictly, you need one custom class per LAF

查看更多
登录 后发表回答