在尊重外观的同时更改JButton的形状 [英] Change JButton Shape while respecting Look And Feel
问题描述
我知道这个问题已经问了一百万遍了,可以通过覆盖paintComponent()
来完成,但是我想知道的是如何在尊重当前外观的同时改变形状.如果要将形状更改为圆形,则还希望按钮看起来像按钮,只是形状不同.
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.
我尝试制作一个JButton,将其重写为paintComponent
,然后将其裁剪为一个圆形,但是我没有在Nimbus LAF
上获得边框效果.
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
.
有更好的方法吗?还是JButton
中有一种方法?
Is there a better way? Or is there a method in JButton
?
推荐答案
对于工程图组件,使用ComponentUI.该UI类具有绘画方法,用于绘画组件.绘制方法使用L& F的设置,这些设置作为属性存储在UIManager中.
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.
要创建您自己的组件,例如从RoundButton
AbstractButton
,您可以创建自己的RoundButtonUI
(可能是ButtonUI
的扩展).在这里,您可以使用普通按钮(例如Button.font
或Button.foreground
)的属性来创建自己的绘制方法,以使用与普通按钮相同的L& F值绘制自己的组件.
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.
在您的RoundButton
类中,您应该实现方法getUIClassID()
,该方法将返回字符串"RoundButtonUI"
.这将导致您使用RoundButtonUI
.
In your RoundButton
class you should implement the method getUIClassID()
which will return the string "RoundButtonUI"
. This causes your RoundButtonUI
to be used.
JButton
本身就是一个很好的例子.
A good example is JButton
itself.
这篇关于在尊重外观的同时更改JButton的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!