简体   繁体   中英

Image Icon in JFrame

ImageIcon img = new ImageIcon(pathToFileOnDisk);
myFrame.setIconImage(img.getImage());

I can't seem to find a way to display a picture stored on the computer when a button is clicked. I am trying to do so by setting an icon to a label, through the code (not properties), as I want to be able to change the picture through the button being clicked again. I would like the picture stored in the project (if possible). I would like help on having a working way to have an image displayed in my JFrame as me trying things and searching on this website for the last 2 hoours didn't help. I would provide code to the button but I constantly delete it as I each method I try doesn't work. I don't know what I am missing in imports either. I have tried these imports:

import java.awt.Color;
import javax.swing.Icon;
import javax.swing.ImageIcon;

and my errors

ImageIcon img = new ImageIcon("C:\Users\(user)\Desktop\pic.png");
//has "illegal escape character" as error
        RescuedImage.setIconImage(img.getImage());
//"cannot find symbol"

I would like to see a working sample with the imports shown if no one wants the headache of this. All I want to be able to do is have a button show an image stored on the computer by using its file location.

To load a file location..

jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\(user)\\Desktop\\pic.png"));

To have the picture saved to .jar, java project, drag the image into the project and you should see it shown (in netbeans it's under source packages)

code to show it as logo for label:

String image = "(pictureName).jpg";
    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(image)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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