更改 JButton 渐变颜色,但仅针对一个按钮,而不是全部
我想更改 JButton
渐变颜色,
我发现了这个, http://java2everyone.blogspot.com/2009 /01/set-jbutton-gradient-color.html,但我只想更改一个按钮的渐变,而不是所有按钮
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以覆盖 JButton 实例的 >paintComponent 方法并绘制其 Graphics 对象,具有以下实现 Paint 接口:
You can override the paintComponent method of the
JButton
instance and paint its Graphics object with one of the following classes that implement the Paint interface:比 mre 答案有一点改进:
A little improvement over mre answer:
TL;DR:这不可能直接实现,但可以通过像 Luca 的答案中那样的解决方法来完成,但是他/她的答案使用了不正确的梯度步骤。下面列出了正确的。
工作方式
Metal LAF 中有一个硬编码的例外。如果
background
属性是UIResource
的子类,则它会被忽略*,并且按钮会使用 UI 属性Button.gradient 中的(也是硬编码的)渐变进行绘制
。否则,如果background
不是UIResource
,则按原样绘制该背景。*除非按钮被禁用,在这种情况下没有渐变,
UIResource
内的颜色用于背景。渐变
按照
MetalButtonUI
的逻辑,我发现它使用的渐变来自UI属性Button.gradient
,其中包含ArrayList
:进一步遵循逻辑,我最终进入了
MetalUtils.GradientPainter.drawVerticalGradient()
。此实现将上述数据解释为*:*假设第二个浮点数为 0.0,否则会绘制更多渐变。
由于这是多阶段渐变,因此无法使用简单的
GradientPaint
来完成,但可以使用LinearGradientPaint
来完成。但是,background
属性仅接受Color
。它甚至不能被欺骗/黑客攻击,因为实际值最终被赋予Graphics.setColor()
而不是Graphics2D.setPaint()
(即使 Metal 是基于 Swing 的并且不是 AWT)死胡同。唯一的解决方案似乎是完全子类化 JButton。TL;DR: it's not possible directly, but can be done with a workaround like in Luca's answer, however his/her answer uses the incorrect gradient steps. The correct ones are listed below.
The way it works
In the Metal LAF there is a hardcoded exception. If the
background
property is a subclass ofUIResource
, it's ignored* and the button is instead painted with the (also hardcoded) gradient from the UI propertyButton.gradient
. Otherwise, ifbackground
is not aUIResource
, that background is painted as-is.*unless the button is disabled, in which case there is no gradient and the color inside the
UIResource
is used for the background.The gradient
Following the logic of
MetalButtonUI
, I found out the used gradient it uses comes from the UI propertyButton.gradient
, which contains theArrayList
:Following the logic even further, I ended up in
MetalUtils.GradientPainter.drawVerticalGradient()
. This implementation interprets the above data as*:*assuming the second float is 0.0, otherwise more gradients are drawn.
Since this is a multi-stage gradient, it can't be done with a simple
GradientPaint
but can be done with aLinearGradientPaint
. However thebackground
property only acceptsColor
. It cannot even be spoofed/hacked because the actual value is eventually given toGraphics.setColor()
and notGraphics2D.setPaint()
(even though Metal is Swing-based and not AWT) Dead End. The only solution seems to subclass JButton altogether.我发现卢卡的回答是最好的。
我只是做了一些改变。我添加了一个淡入淡出变量,以便选择如果需要,可以不选择纯白色。
这是总代码:
luca's answer I found to be the best.
I just made a few changes. I added a fade variable for the option of not going to pure white if desired.
Here is the total code: