Change JButton Shape while respecting Look And Feel

风流意气都作罢 提交于 2019-12-12 18:13:13

问题


I know this question has been asked a million times, and can be done by overriding paintComponent(), but what I want to know is how to change the shape while respecting the current Look And Feel. If I want to change the shape to a circle, I also want the button to look like a button, just with a different shape.

I tried making a JButton, the overriding paintComponent, then clipping it to a circle, but I didn't get the border effects on Nimbus LAF.

Is there a better way? Or is there a method in JButton?


回答1:


For drawing components a ComponentUI is used. This UI class has a paint method and is used to paint the component. The paint method uses the settings of the L&F which are stored as properties in the UIManager.

To create your own component RoundButton extending from e.g. AbstractButton you can create your own RoundButtonUI (maybe extending from ButtonUI). Here you can create your own paint method using the properties of a normal button like Button.font or Button.foreground to draw your own component with the same L&F values as a normal button.

In your RoundButton class you should implement the method getUIClassID() which will return the string "RoundButtonUI". This causes your RoundButtonUI to be used.

A good example is JButton itself.



来源:https://stackoverflow.com/questions/7863982/change-jbutton-shape-while-respecting-look-and-feel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!