我正在编写一个程序,需要一个上面有图像的按钮,但是,到目前为止,我还无法让它工作。我检查了该网站上的其他几篇帖子,包括如何将图像添加到 JButton https://stackoverflow.com/questions/4801386/how-do-i-add-an-image-to-a-jbutton.
我的代码:
public class Tester extends JFrame
{
public Tester()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
setTitle("Image Test");
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton();
try
{
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
button.setIcon(new ImageIcon(img));
}
catch (IOException ex) {}
button.setBounds(100,100,100,100);
panel.add(button);
}
public static void main(String[] args)
{
Tester test = new Tester();
test.setVisible(true);
}
}
当此代码运行时,会出现错误: Exception in thread "main" java.lang.IllegalArgumentException: input == null!此错误发生在以下行:
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
我不认为这个错误是由于 java 代码找不到该文件,因为我的 Images 文件夹位于 src 文件夹中(我使用的是 Eclipse),如上面链接所建议的。
有谁知道问题可能是什么?
Thanks.
使用 Eclipse 时,您无需将图像保存到源文件夹相反,你创建一个Source Folder
以此目的。有关如何操作的信息,请参阅此链接将图像添加到 Eclipse 中的资源文件夹 https://stackoverflow.com/a/9278270/1057230.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)