如何在 Java 的 JButton 中插入 ImageIcon

在构造函数中声明 JButton 时,可以在 java> 中
JButton b = new JButton(Icon icon);
ou:

JButton b = new JButton(字符串文本,图标图标);
示例:

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
导入 javax.swing.JFrame;

公共类 JButtonTest 扩展 JFrame{

JButton b = new JButton(Open”, new ImageIcon(icon.png”));

public JButtonTest(){
JFrame frame = new JFrame(JFrame test”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
b.setPreferredSize(new Dimension(150,100));
frame.getContentPane().add(b);
frame.pack();
}

public static void main(String[] args) {
new JButtonTest();
}
}
Output
在java的jbutton中插入图像或图标”

方法 setIcon

创建按钮后,也可以通过调用 JButton.setIcon(ImageIcon img)在 AbstractButton.

ImageIcon image = new ImageIcon(icon.png”);
b.setIcon(图像);

Import ImageIcon from classpath

要从文件夹加载图像,请使用 ImageIO.read()。此方法将图像(资源)的路径作为存储在项目中的参数。爪哇岛。方法 getClass().getResource() 使用类装入器来加载资源。这意味着此资源必须位于项目的根目录中才能加载。

将图像或图标添加到类路径”

try {
Image img = ImageIO.read(getClass().getResource(/icon.png”));
b.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
References:
Oracle 文档: AbstractButton: setIcon 方法
Java 教程: 读取图像
Stackoverflow: getclass.getressource