This is my code..
But the image doesnt appear on the frame when i run the program
Please help

    JLabel label = new JLabel();
    String path = "C:/Documents and Settings/Administrator/My Documents/My Pictures//22.bmp";
            try {
            URL url = new URL(path);
            BufferedImage image = ImageIO.read(url);
            label = new JLabel(new ImageIcon(image));
            } catch(Exception e){}

Recommended Answers

All 7 Replies

Well, you are neither adding the JLabel to anything, nor "refreshing" whatever you might have wanted to add it to.

Edit: And, if you want to change a Lable that already exists somewhere in the GUI, then don't use new JLabel() in the try/catch block. If you do, you have created a new JLabel, but the original still exists and is still a part of the GUI.

Instead of

URL url = new URL( path );
BufferedImage image = ImageIO.read( url );

try

File imageFile = new File( path );
BufferedImage image = ImageIO.read( imageFile );

Generally URLs are only used for the internet, use Files for local stuff...

Have added the JLabel to my container..

Did nt include that part of my code as it dint seem important..

What was about the "REFRESHING" that you mentioned..

I am sorry was unable 2 get it

Generally URLs are only used for the internet, use Files for local stuff...

True, to an extent, but it still works with a url, as it will be given a "file://" url, rather than an "http://" url. It is still valid. His problem lies either in that he is not adding the JLabel, at all, is not calling validate() on whatever he added it to, or, because he is calling "new JLabel" in the try block, he is not actually changing the JLabel that already appears in the GUI, but rather creating a new one and not doing anything with it. (I believe, anyway.)

Have added the JLabel to my container..

Did nt include that part of my code as it dint seem important..

What was about the "REFRESHING" that you mentioned..

I am sorry was unable 2 get it

call validate() on the component you added the label to.

Also, replace that

} catch (Exception e) {}

with

} catch (Exception e) {
    e.printStackTrace();
}

Then tell us if any error occurs. Simply swallowing errors, like you are doing, is very, very, very, very bad practice.

True, to an extent, but it still works with a url, as it will be given a "file://" url, rather than an "http://" url. It is still valid.

I didn't know that - thanks masijade :)

Thanxx for your help..!!
My problem is solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.