为什么setIcon不在JButton上显示图像? [英] Why isn't setIcon displaying image on JButton?
问题描述
我发誓我到处寻找并且谷歌上网了好几个小时。我已经为所有按钮添加了 actionListeners
,当点击一个按钮时,我想给它一个带有 setIcon(image)的图像
像这样:
I swear I've looked everywhere and have been googling for hours. I have added actionListeners
to all buttons, and when one is clicked, I want to give it an image with setIcon( image )
like so:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
ImageIcon icon = new ImageIcon(getClass().getResource("/Images/" +letter+ ".PNG"));
button.setIcon(icon );
}
1)我知道它正在检索图像,因为按钮.getIcon()
给我一些类似的文件:/Users/path/to/Images/X.PNG
。我在设置图标之前和之后检查过它是否为空,之后它不为空。
1) I know it's retrieving the image because button.getIcon()
gives me something like file:/Users/path/to/Images/X.PNG
. I've checked if it's null before and after I've set the icon and it's not null afterward.
2)除了<$我还试过了setIcon的其他变种c $ c> getClass()... 和 ImageIO.read ...
和 BufferedImage
。
3)我不想添加更多代码,因为我甚至不确定其他相关内容。我希望你的一些推测
3) I don't want to add more code because I'm not even sure what else is relevant. I was hoping for some of your speculations
4)在eclipse中,我将输出文件夹更改为 src
(而不是 bin
),这就是我的 Images
文件夹的位置。
4) In eclipse, I changed my output folder to src
(instead of bin
), and that's where my Images
folder is.
推荐答案
我认为我遇到了同样的问题。我正在使用Eclipse,在JGrasp中测试我的代码并且它有效。原来Eclipse需要Project文件夹中的资源,而不是SRC或BIN。
I had a the same problem, I think. I was using Eclipse, tested my code in JGrasp and it worked. Turns out Eclipse wants the resources in the Project folder, not the SRC or BIN.
这篇关于为什么setIcon不在JButton上显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!