ImageIcon不能与我合作

时间:2014-06-14 08:12:41

标签: java swing imageicon

我编写了非常简单的代码来显示葡萄的图标,但代码仍然没有显示任何内容

这是我的代码

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 个答案:

答案 0 :(得分:2)

如果在最后调用frame.setVisible(true)后仍无法看到图片图标,请查看我在同一上下文中提问的其他帖子。


尝试

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

值得一读How to Use Icons,以下是直接来自那里的样本。

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

阅读更多Loading Images Using getResource,直观地解释。

例如名为omega的目录中的类文件。 omega/images目录中的图像。

enter image description here