views:

88

answers:

2

I want to create a button class and use a ButtonUI to render it instead of overriding the paint component method. I do not want to use this ButtonUI for ALL JButtons. Is that possible? I've only ever seen UIManager.put("ButtonUI","MyCustomButtonUI"), but does this affect ALL JButton rendering? Is it possible to limit the scope of the put operation?

+3  A: 

JButton.setUI(ButtonUI) sets the UI for just one JButton. Use that in conjunction with a factory:

public static JButton createStyledButton(String text) {
   JButton button = new JButton(text);
   button.setUI(STYLE_UI);
   return button;
}     

EDIT: Or, since you say it's constant for a certain subclass, just call setUI() from the constructor for that subclass.

Another alternative might be to override the method getUIClassID() in your subclass. This will probably allow you to still use the UIManager to choose which style to use, but I haven't tested it.

Mark Peters
A: 

Well, you can, in your ButtonUI class, check the real component class being given to you and only override default behaviour for our desired subclass, through instanceof or any other mechanism.

But, if you, like me, don't like repeated calls to instanceof use another trick. As your button subclasses JButton, it also subclasses JButton and AbstractButton, allowing you to call AbstractButton#setUI in your constructor or somewhere else, allowing a specific renderer, totally distinct from LnF application.

Riduidel