swing-Java:使用图像作为按钮
我想将图像用作Java中的按钮,而我尝试这样做:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
但这仍然显示图像后面的实际按钮,我只想将图像用作按钮,我该怎么做?
3sdmx asked 2020-01-02T19:48:12Z
9个解决方案
28 votes
像这样删除边框:
button.setBorder(BorderFactory.createEmptyBorder());
然后还有内容1:
button.setContentAreaFilled(false);
1:来自@ 3sdmx添加到问题中的解决方案
jzd answered 2020-01-02T19:48:39Z
9 votes
建议将“图像”设置为标签,并将鼠标侦听器添加到标签以检测点击。
例:
ImageIcon icon = ...;
JLabel button = new JLabel(icon);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
... handle the click ...
}
});
thotheolh answered 2020-01-02T19:49:04Z
1 votes
buttonIcon.setBorder(newEmptyBorder(0,0,0,0));
StanislavL answered 2020-01-02T19:49:23Z
1 votes
button.setBorderPainted( false );
camickr answered 2020-01-02T19:49:39Z
1 votes
通过将contentAreaFilled属性设置为False,可以在netbeans中轻松完成此操作
unleashed answered 2020-01-02T19:49:59Z
1 votes
BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));
button = new JButton(new ImageIcon(buttonIcon));
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
Vladimir answered 2020-01-02T19:50:14Z
1 votes
只是写这个
button.setContentAreaFilled(false);
Adham Gamal answered 2020-01-02T19:50:34Z
0 votes
据我所知,没有简便的方法,您将需要重写JButton类的“ paintComponent”方法来修饰图像,如果您只想显示图像并表现得像按钮,则可以添加 一个JPanel绘制图像(clicky)并添加一个MouseListener / MouseAdapter来处理“ mousePressed”事件
Harima555 answered 2020-01-02T19:50:55Z
0 votes
我按照以下步骤操作,可以成功创建“ ImageButton”。
创建Border
添加了动作监听器
设置图像图标(请注意,我已将Border图标放置在src \ main \ resources文件夹中,并使用类加载器加载了)。 项目结构如下。
设置一个空的Border
禁用内容区域填充
禁用对焦能力
添加到内容窗格
PFB对我有用的代码
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);
上面的代码产生的输出按钮如下
sunil answered 2020-01-02T19:51:54Z