如何在JButton上放置图像? [英] How to put an image on a JButton?

查看:85
本文介绍了如何在JButton上放置图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,要求我有一个按钮,上面有一个图像,但到目前为止,我还没有能够让它工作。我已经查看了该网站上的其他几篇帖子,包括我该怎么做将图像添加到JButton

我的代码:

I am writing a program that requires I have a button with an image over top of it, however, so far, I have not been able to get it to work. I have checked several other posts on this site, including How do I add an image to a JButton.
My Code:

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);
    }
}

当此代码运行时,会出现错误:异常threadmainjava.lang.IllegalArgumentException:input == null!此错误发生在以下行:

When this code runs, an error results: Exception in thread "main" java.lang.IllegalArgumentException: input == null! This error occurs at the line:

Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));

我不认为这个错误是由于java代码找不到文件,因为我的Images文件夹位于src文件夹中(我正在使用Eclipse),如上面链接所推荐的那样。


有没有人对这个问题有什么想法?

谢谢。

I don't think that this error is due to the file not being found by java code, as my Images folder is in the src folder (I am using Eclipse) as recommended by the above link.
Does anyone have any ideas to what the problem may be?
Thanks.

推荐答案

使用Eclipse时,不要将图像保存到 src文件夹而是为此目的创建源文件夹。请参阅此链接,了解如何将图像添加到Eclipse中的资源文件夹

While using Eclipse, you don't keep your images into src folder instead you create a Source Folder for this purpose. Please refer to this link regarding how to add images to resource folder in Eclipse.

这篇关于如何在JButton上放置图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆