Java:使用图像作为按钮
我想在Java中使用图像作为按钮,我尝试这样做:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
但这仍然显示图像后面的实际按钮,我只希望图像充当按钮,我该怎么做?
I would like to use an image as a button in Java, and I tried to do this:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
But this still shows the actual button behind the image, I would only like the image to function as the button, how can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
像这样删除边框:
然后删除内容1:
1:取自@3sdmx添加到问题的解决方案
Remove the border like so:
and then also the contents1:
1: Taken from the solution added to the question by @3sdmx
建议将图像设置为标签,并向标签添加鼠标侦听器以检测点击。
例子:
A suggestion would be to set the Image as a label and add a mouse listener to the label to detect clicks.
Example:
buttonIcon.setBorder(new EmptyBorder(0,0,0,0));
buttonIcon.setBorder(new EmptyBorder(0,0,0,0));
通过将 contentAreaFilled 属性设置为 False,可以在 netbeans 中轻松完成此操作
This can be done easily in netbeans by setting the contentAreaFilled Property to False
就写这个
just write this
据我所知,没有简单的方法可以做到这一点,您需要重写 JButton 类的“paintComponent”方法来绘制图像,如果您只想显示图像并表现得像按钮,您可以添加一个 JPanel 绘制图像(clicky)并添加 MouseListener /MouseAdapter 处理“mousePressed”事件
As far i know, there is no easy way of doing it, you will need to override the "paintComponent" method of the JButton class to aint your image, if you only want to display an image and behave like a button, you can add a JPanel wich draws the image (clicky) and add a MouseListener/MouseAdapter to handle the "mousePressed" event
我按照以下步骤操作,可以成功创建“ImageButton”。
JButton
info.png
图标放在 src\main\resources 文件夹中并使用类加载器加载)。项目结构如下。Border
PFB 对我有用的代码
上面代码产生的输出按钮如下
I followed below steps and i could create an 'ImageButton' successfully.
JButton
info.png
icon in the src\main\resources folder and loaded using class loader). The project structure is as here.Border
PFB the code that worked for me
The output button resulted from above code is as below