简体   繁体   English

如何使用jbutton将jlabel的图标设置为背景图像?

[英]How can I set the icon of jlabel as background image using a jbutton?

I'm using Jframe form for this program and here's the button code I've tried. 我正在为此程序使用Jframe表单,这是我尝试过的按钮代码。 When I ran the program and clicked the button nothing happens. 当我运行程序并单击按钮时,没有任何反应。 Pls help. 请帮助。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    ImageIcon icondir = new ImageIcon("C:\\Users\\Awesome\\Desktop\\myaJbQq.jpg");
    ID_Background.setIcon(icondir);
}                       

This file (image) C:\\\\Users\\\\Awesome\\\\Desktop\\\\myaJbQq.jpg does not exists. 此文件(图像) C:\\\\Users\\\\Awesome\\\\Desktop\\\\myaJbQq.jpg不存在。

The problem with ImageIcon is that is not throwing any exception if the file/resource is missing. ImageIcon问题是,如果文件/资源​​丢失,则不会引发任何异常。 Try to load the icon this way: 尝试通过以下方式加载图标:

ImageIcon icondir = new ImageIcon(
    ImageIO.read(
        new File("C:\\Users\\Awesome\\Desktop\\myaJbQq.jpg")));

You will have for sure an exception: 您肯定会有例外:

Exception in thread "main" javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    ...
ID_Background.repaint();

Should fix your issue. 应该解决您的问题。 If not, I'm going to need more code than what you've provided (what the ID_Background is, how your GUI is setup, etc). 如果没有,我将需要比您提供的代码更多的代码(ID_Background是什么,GUI的设置方式等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM