我正在编写一个程序,要求我有一个按钮,上面有一个图像,但是,到目前为止,我还无法让它工作。我检查了该站点上的其他几个帖子,包括 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),正如上面链接所推荐的那样。
有没有人对问题可能有任何想法?
谢谢。
最佳答案
在使用 Eclipse 时,您不会将图像保存在 src 文件夹 中,而是为此目的创建一个 Source Folder
。请参阅此链接了解如何 add images to resource folder in Eclipse .
关于java - 如何将图像放在 JButton 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12691832/