[英]How do I use JLabels?
When I try to create a JLabel, it displays text perfectly and is placed fine within the container, but if I try to add an image to the label, nothing shows up. 当我尝试创建一个JLabel时,它会完美地显示文本并在容器中正确放置,但如果我尝试将图像添加到标签中,则不会显示任何内容。
ImageIcon icon = new ImageIcon("../media/link_walk.png", "hh");
JLabel j = new JLabel("hello");
j.setIcon(icon);
p.add(j);
If your app. 如果你的应用程序 is in Jar files and the image is an application resource, it will also be in a Jar file. 在Jar文件中,图像是应用程序资源,它也将在Jar文件中。
The ImageIcon
constructor that accepts a String
presumes the String
represents a file path/name. 接受String
的ImageIcon
构造函数假定String
表示文件路径/名称。 A File
object cannot be established to a resource in a Jar. 无法在Jar中的资源上建立File
对象。 For resources in a Jar, it is necessary to access them by URL
. 对于Jar中的资源,必须通过URL
访问它们。
To get an URL
to something in a Jar, use something like.. 要获取Jar中某些内容的URL
,请使用类似的内容。
URL urlToImage = this.getClass().getResource("/media/link_walk.png");
// Check the URL!
System.out.println("urlToImage is " + urlToImage);
Then use the ImageIcon
constructor that accepts an URL
. 然后使用接受URL
的ImageIcon
构造函数。
JLabels are not opaque by default, and so background color changes won't be seen unless you make them opaque via setOpaque(true). 默认情况下,JLabel不是不透明的,因此除非您通过setOpaque(true)使它们变得不透明,否则将无法看到背景颜色更改。 Also the preferredSize of the JLabel will depend on the text it holds. 此外,JLabel的首选大小取决于它所拥有的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.