【发布时间】: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