【问题标题】:How to set a image icon to JButton?如何将图像图标设置为 JButton?
【发布时间】:2016-01-21 17:23:23
【问题描述】:

我想为 JButton 设置一个图像图标,这里是我尝试过的代码:

public class Calculator {

    public static JFrame f;

    Calculator() throws IOException{

        JButton b;

        f = new JFrame();
        Image play = ImageIO.read(getClass().getResource("images/play.png"));
        b = new JButton(new ImageIcon(play));

        b.setBounds(250,250,75,20);

        f.add(b);
        f.setSize(500,500);
        f.setLayout(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws IOException {

        new Calculator();
    }
}

程序运行正常,没有错误,但没有出现图像。

我认为图片的网址是错误的。

我使用的是 netbeans,所以我在源包目录中创建了一个名为 images 的文件夹。

【问题讨论】:

  • 尝试在程序中显示图像的绝对路径,并将其与实际路径进行比较。它们匹配吗?
  • getClass().getResource("images/play.png") 通常最好在字符串前面加上/ 像这样getClass().getResource("/images/play.png")
  • f.setLayout(null); Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
  • @AndrewThompson 谢谢,通过在字符串前面加上斜杠解决了这个问题。
  • 很高兴你把它整理好了。 :) 现在整理这些布局。 ;)

标签: java swing netbeans jbutton embedded-resource


【解决方案1】:

可以通过在资源路径前加上斜杠来解决该问题:

Image play = ImageIO.read(getClass().getResource("/images/play.png"));

这表示image 文件夹位于所有资源的根位置,与当前类位置无关。

部分归功于Andrew Thompson 的评论。

【讨论】:

    【解决方案2】:

    试试b.setIcon(new ImageIcon(getClass().getResource("images/play.png")));

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      相关资源
      最近更新 更多