Java - 在 JPanel 中设置不透明度
假设我想让 JPanel %20 的不透明度可见?我的意思不是 setOpaque(绘制或不绘制)或 setVisible(显示或隐藏)...我的意思是使其透明 JPanel.. 你知道吗?
这可能吗?
Let's say I want to make the opacity of a JPanel %20 viewable? I don't mean setOpaque (draw or not draw) or setVisible (show or hide)... I mean make it see-through JPanel.. you know?
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要为 Color 对象设置“alpha”值:
但是,这仍然无法正常工作,因为 Swing 无法正确绘制透明背景,因此您需要进行自定义绘制。基本逻辑是:
查看具有透明度的背景有关实际绘画问题以及上述代码为何解决该问题的更多信息。该链接还包含一个自定义的可重用类,可以为您完成上述绘制。
You need to set the "alpha" value for your Color object:
However, this will still not work properly as Swing doesn't paint transparent background properly so you need to do custom painting. The basic logic is:
Check out Backgrounds With Transparency for more information on the actual painting problem and why the above code solves the problem. The link also contains a custom reusable class that does the above painting for you.
使用颜色的 alpha 属性。
例如:
将创建黑色,alpha 为 64(透明度)
结果如下:
代码
这是没有的 它看起来像这样:
Use the alpha attribute for the color.
For instance:
Will create a black color, with 64 of alpha ( transparency )
Resulting in this:
Here's the code
With out it it looks like this:
其中aWindow是Swing组件,aFloat是不透明度。
Where aWindow is the Swing component, and aFloat is the opacity.
它在 Windows 7 上效果不太好。Alpha
通道只是使颜色变亮。
当元素更新为具有 Alpha 通道的颜色时,计算机会感到困惑并重置更新元素的背景而不使用 Alpha。 接下来我要尝试一下
。
It doesn't work so well on windows 7.
the alpha channel just lightens the color.
when an element is updated on a color with an alpha channel, the computer gets confused and resets the background of the updated element without an alpha. I'm going to try
next.
如果您有一个自定义面板并希望整个面板是半透明的,我建议您像这样重写它的paintComponent方法:
If you have a custom panel and want the whole thing to be semi-transparent, I advise you to do override its method paintComponent like this :
如何重写 JPanel 的 PaintComponent 方法(为了做到这一点,您必须对 JPanel 本身进行子类化并实现您自己的 PaintComponent 方法),在 PaintComponent 中您可以检索组件的缓冲图像,从那里您可以操作 alpha缓冲图像并将其绘制回 JPanel。我很久以前就红过。仍在寻找代码。
How about override the paintComponent method of the JPanel(in order to do this you have to sub class the JPanel itself and implement your own paintComponent method) inside the paintComponent you can retrieve a buffered image of the component, from there you can manipulate the alpha of the buffered image and paint it back to the JPanel. I have red this long time ago. Still looking for the code.