ImageIcon无法与我一起使用 [英] ImageIcon does not work with me
问题描述
我编写了非常简单的代码来显示葡萄的图标,但是代码仍然没有显示任何内容
i wrote very simple code to display an icon of the grapes but still the code doesn't show me anything
这是我的代码
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);
}
}
推荐答案
如果即使在最终致电frame.setVisible(true)
之后仍然看不到图像图标,那么请查看我在同一上下文中被问到的其他帖子.
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.
-
尝试
// 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; } }
了解更多信息使用getResource加载图像,其中视觉上解释它.
Read more Loading Images Using getResource where it is explained visually.
例如名为omega的目录中的类文件.
omega/images
目录中的图片.For e.g. Class file in directory named omega. Image in
omega/images
directory.这篇关于ImageIcon无法与我一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!