-->

ImageIcon does not work with me

2019-03-04 17:36发布

问题:

i wrote very simple code to display an icon of the grapes but still the code doesn't show me anything

here is my code

import javax.swing.*;
import java.awt.*;

public class Code {
ImageIcon ii = new ImageIcon("image/grapes2.jpg");
JLabel label = new JLabel("Grapes", ii, SwingConstants.CENTER);
JFrame frame = new JFrame("ImageIcon");

public void ui(){
    label.setHorizontalTextPosition(SwingConstants.CENTER);
    label.setVerticalTextPosition(SwingConstants.BOTTOM);
    label.setIconTextGap(5);

    label.setOpaque(true);
    label.setBackground(Color.GRAY);

    frame.setSize(2300,2300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(label);

}

}

回答1:

If image icon is not visible even after calling frame.setVisible(true) in the end then have a look at my another posts that is asked in the same context.

  • How to retrieve image from project folder?

  • Read image from another directory


Try

// Read from src/image folder
ii = new ImageIcon(ImageIO.read(getClass().getResource("/image/grapes2.jpg")));
label.setIcon(ii);

It's worth reading How to Use Icons and here is the sample directly from there.

ImageIcon icon = createImageIcon("images/middle.gif",
                             "a pretty but meaningless splat");
label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
...
label3 = new JLabel(icon);

/** 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;
    }
}

Read more Loading Images Using getResource where it is explained visually.

For e.g. Class file in directory named omega. Image in omega/images directory.