Ken
Ken

Reputation: 287

JLabel Icon not shown

I am trying to display an image in my application...

    picture = new JLabel("No file selected");
    picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
    picture.setHorizontalAlignment(JLabel.CENTER);

    scrollPane.setViewportView(picture);

    ImageIcon icon = new ImageIcon("map.jpg");
    picture.setIcon(icon);
    if (picture.getIcon() != null)                   // to see if the label picture has Icon
        picture.setText("HERE IS ICON");

When I run that code, only the "HERE IS ICON" text displayed. Sorry if this question sounds so dumb, but I really have no clue of why the image icon is not displayed :(

Upvotes: 2

Views: 6788

Answers (3)

matheuslf
matheuslf

Reputation: 309

You can do that:

ImageIcon icon = createImageIcon("map.jpg", "My ImageIcon");

if (icon != null) {
    JLabel picture = new JLabel("HERE IS ICON", icon, JLabel.CENTER);
    picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
    picture.setHorizontalAlignment(JLabel.CENTER);

    scrollPane.setViewportView(picture);
}

The createImageIcon method (used in the preceding snippet) finds the specified file and returns an ImageIcon for that file, or null if that file couldn't be found. Here is a typical implementation:

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

Upvotes: 2

mprivat
mprivat

Reputation: 21902

You need to make sure map.jpg exists as a file. If you want to be sure (for testing purposes only), try to use the full path. The way you have it, the path is relative to the application's start directory.

You can double check if it exists with this:

System.out.println(new java.io.File("map.jpg").exists());

Upvotes: 3

Extreme Coders
Extreme Coders

Reputation: 3511

The file map.jpg might not be in the same package(folder) as the java file. Check it.

Upvotes: 0

Related Questions