如何将图片添加到JButton?

50

我正在尝试为JButton添加一张图片,但不确定缺少了什么。当我运行以下代码时,该按钮的外观与没有添加任何图像属性的情况下创建的按钮完全相同。Water.bmp位于我的项目文件夹的根目录中。

ImageIcon water = new ImageIcon("water.bmp");
    JButton button = new JButton(water);
    frame.add(button);

那应该可以运行...你能否尝试使用ImageIcon构造函数的URL形式并查看它的效果?可能是因为某些原因无法找到图像文件。 - Cameron Skinner
是的,现在它正在运作。代码没有做任何更改。感谢大家的建议。 - kevinstueber
11个回答

79

我认为你的问题在于图像的位置。你应该将它放置在你的源代码中,然后这样使用:

  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/文件夹中。

3
我不知道为什么,但这对我也没有起作用。我甚至建立了一个函数来在目录中搜索所需的文件并找到它们,但仍然没有图标。所以,我只使用了以下代码:button1.setIcon("path/pic.png"); 这样可以正常运行。你有任何想法吗? - Yannic Hansen

18

@Rogach

而且您可能想添加:

// to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);

7

看起来是位置问题,因为那段代码完全可以添加图标。

由于我不知道您的文件夹结构,建议添加一个简单的检查:

File imageCheck = new File("water.bmp");

if(imageCheck.exists()) 
    System.out.println("Image file found!")
else 
    System.out.println("Image file not found!");

这样做的好处是,如果您的路径名不正确,它会告诉您而不是什么都不显示。如果文件不存在,则应抛出异常。

6
您需要把图片放在资源文件夹中,然后使用以下代码:
JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));

3
public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

或者使用这段代码

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }

6
太过复杂了。按钮已经内置了添加图标的机制,为什么要创造额外的问题呢? - Rogach
@Rogach 不是特别针对这个问题,但在我的情况下,进一步控制图像放置在按钮中的位置非常有用。 - Aldo Canepa

2

我只做了一件事,这对我起了作用。检查你的代码中是否有这个方法。

setResizable(false);

如果它是假的,将其改为真,并且它就可以正常工作了...

希望对你有所帮助...


1
框架是否可调整大小并不重要。 - kleopatra
是的,你可能是对的..但是当你有一个Borderlayout然后你做出这个声明..你限制了框架..因此如果你使它为真,它将给你的框架空间。 - Dan

2
buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));

1
这段代码对我有效:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);

1
//paste required image on C disk
JButton button = new JButton(new ImageIcon("C:water.bmp");

1
例如,如果您在文件夹res/image.png中有图像,则可以编写以下内容:
try
{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("image.png");
    // URL input = classLoader.getResource("image.png"); // <-- You can use URL class too.
    BufferedImage image = ImageIO.read(input);

    button.setIcon(new ImageIcon(image));
}
catch(IOException e)
{
    e.printStackTrace();
}

一行代码:

try
{
    button.setIcon(new ImageIcon(ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("image.png"))));
}
catch(IOException e)
{
    e.printStackTrace();
}

如果图片比按钮大,则不会显示。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接