ImageIcon does not work with me

瘦欲@ 提交于 2019-12-20 07:22:30

问题


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.



来源:https://stackoverflow.com/questions/24217961/imageicon-does-not-work-with-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!