如何将图像添加到 JButton [英] How do I add an image to a JButton

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

问题描述

我正在尝试将图像添加到 JButton,但我不确定我错过了什么.当我运行以下代码时,该按钮看起来与我在没有任何图像属性的情况下创建它时完全相同.Water.bmp 位于我的项目文件夹的根目录中.

I am trying to add an image to a JButton and I'm not sure what I'm missing. When I run the following code the button looks exactly the same as if I had created it without any image attribute. Water.bmp is in the root of my project folder.

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

推荐答案

我认为你的问题出在图片的位置上.你应该把它放在你的源代码中,然后像这样使用它:

I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

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

In this example, it is assumed that image is in src/resources/ folder.

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

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