简体   繁体   English

如何给JButton同时提供ImageIcon和背景色?

[英]How to give a JButton both an ImageIcon and background color?

Is there a way to do both 有两种方法都可以

button.setBackground(Color.green.darker());

and

button.setIcon(new ImageIcon(buttonImg.getScaledInstance(15, 15, Image.SCALE_SMOOTH)));

so that both the image and the background color are visible? 这样图像和背景色都可见? Is there some sort of transparency setting on the button's image that I'm missing? 我缺少按钮图像上的某种透明度设置吗? Any help would be greatly appreciated. 任何帮助将不胜感激。

EDIT: 编辑:

Here is the image I'm trying to use. 这是我要使用的图像。 As you can see, it has transparency. 如您所见,它具有透明度。 http://www.clipartlord.com/wp-content/uploads/2013/09/bomb3.png http://www.clipartlord.com/wp-content/uploads/2013/09/bomb3.png

What I am trying to get is the image to show up on the Button with the background color of green filling in the transparency. 我想要得到的是显示在Button上的图像,背景颜色为绿色,并填充了透明度。 Right now when I try to do it, if I add the image at all, the background color is not visible whatsoever. 现在,当我尝试执行此操作时,如果完全添加图像,则背景色将不可见。 But if I don't add the image, the background color is visible. 但是,如果我不添加图像,则背景色是可见的。 I hope this helps. 我希望这有帮助。

Probably the LookAndFeel does not support what you want to achieve. LookAndFeel可能不支持您要实现的目标。 Here is an image from the meta theme, on the left, and osx aqua theme. 这是来自meta主题(左侧)和osx aqua主题的图像。

两种不同,右侧是osx aqua,左侧是金属

If you want all of your JButton backgrounds to change you can try using a LookAndFeel that supports changing the UI. 如果要更改所有 JButton背景,可以尝试使用支持更改UI的LookAndFeel。 Unfortunately the aqua them does not let you change the default background for a button even using the UIManager#set 不幸的是,即使使用UIManager#set ,aqua它们也不允许您更改按钮的默认背景

If you only want to do one button, you can change the button UI. 如果只想做一个按钮,则可以更改按钮UI。

button.setUI(new BasicButtonUI());

That one doesn't look too nice, you can set the UI to one from another LookAndFeel, 看起来不太好,您可以将UI设置为另一个LookAndFeel的UI,

button.setUI(new MotifButtonUI());

(Also doesn't look very nice, but now it buttons .) (也没有看起来非常漂亮,但现在它的按钮 。)

Finally you can also create your own ButtonUI, or do some custom painting. 最后,您还可以创建自己的ButtonUI,或进行一些自定义绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM