我想在Java中使用一张图片作为按钮,我尝试了以下代码:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
但是这仍然显示了图像后面的实际按钮,我只希望图像作为按钮起作用,我该怎么做?
按照以下方式移除边框:
button.setBorder(BorderFactory.createEmptyBorder());
然后还有内容1:
button.setContentAreaFilled(false);
1: 取自@3sdmx在问题中添加的解决方案
一个建议是将图像设置为标签,并向标签添加鼠标监听器以检测点击。
示例:
ImageIcon icon = ...;
JLabel button = new JLabel(icon);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
... handle the click ...
}
});
button.setBorderPainted( false );
只需写入此内容
button.setContentAreaFilled(false);
BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));
button = new JButton(new ImageIcon(buttonIcon));
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
buttonIcon.setBorder(new EmptyBorder(0,0,0,0));
按钮图标.setBorder(new EmptyBorder(0,0,0,0));
通过将contentAreaFilled属性设置为False,可以在NetBeans中轻松完成此操作。
我按照以下步骤成功地创建了一个“ImageButton”:
JButton
info.png
图标放置在 src\main\resources 文件夹中,并使用类加载器进行加载)。项目结构如下。Border
以下是对我有效的代码:
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Info clicked");
}
});
String iconfilePath = this.getClass().getClassLoader().getResource("info.png").getFile();
btnNewButton.setIcon(new ImageIcon(iconfilePath));
btnNewButton.setBounds(10, 438, 39, 31);
btnNewButton.setBorder(BorderFactory.createEmptyBorder());
btnNewButton.setContentAreaFilled(false);
btnNewButton.setFocusable(false);
contentPane.add(btnNewButton);