如何将图像图标设置为 JButton?

How to set a image icon to JButton?

我想给JButton设置一个图片图标,这里是我试过的代码:

public class Calculator {

    public static JFrame f;

    Calculator() throws IOException{

        JButton b;

        f = new JFrame();
        Image play = ImageIO.read(getClass().getResource("images/play.png"));
        b = new JButton(new ImageIcon(play));

        b.setBounds(250,250,75,20);

        f.add(b);
        f.setSize(500,500);
        f.setLayout(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws IOException {

        new Calculator();
    }
}

程序运行正常,没有报错,但是没有出现图像。

我认为图片 url 有误。

我使用的是netbeans,所以我在源码包目录下创建了一个名为images的文件夹。

试试 b.setIcon(new ImageIcon(getClass().getResource("images/play.png")));

可以通过在资源路径前加上斜杠来解决这个问题:

Image play = ImageIO.read(getClass().getResource("/images/play.png"));

这表示 image 文件夹位于所有资源的根位置,与当前 class 位置无关。

部分致谢来自 Andrew Thompson 的评论。