我正在尝试将图像添加到 JButton,但我不确定我缺少什么。当我运行以下代码时,按钮看起来与我创建它时没有任何图像属性完全相同。 Water.bmp 位于我的项目文件夹的根目录中。
ImageIcon water = new ImageIcon("water.bmp");
JButton button = new JButton(water);
frame.add(button);
最佳答案
我认为您的问题在于图像的位置。你应该把它放在你的源代码中,然后像这样使用它:
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
button.setIcon(new ImageIcon(img));
} catch (Exception ex) {
System.out.println(ex);
}
在此示例中,假设图像位于 src/resources/文件夹中。
关于java - 如何将图像添加到 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4801386/