[英]I can't get my icon to show up in my JLabel swing component
以下是将图标放置在JLabel Swing组件中的Java Swing代码。
package com.TheMcLeodgrp;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public Main() throws HeadlessException {
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
Icon icon = new ImageIcon("myIcon.gif");
JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);
JLabel label2 = new JLabel("Address :", JLabel.LEFT);
label2.setIcon(new ImageIcon("myIcon.gif"));
getContentPane().add(label1);
getContentPane().add(label2);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
这是一个简单的标签程序,其他所有东西都可以正常工作。 当我运行程序时,图标(myIcon.gif)不会显示在标签中。 我正在从标准Eclipse IDE运行它,而myIcon.gif位于一个文件夹中-即; 图片/ myIcon.gif。 好像我在这里错过了一些简单的事情,但我不知道。 我是否需要将图标放置在应用程序中的其他位置。
我认为以下文章将在解释如何加载图像资源方面做得更好:
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/icon.html
我将在教程中第二次推荐@eugener。 另外,尝试使用相对路径,并检查构造ImageIcon
的结果:
JLabel label2 = new JLabel("Address :", JLabel.LEFT);
ImageIcon icon = new ImageIcon("images/myIcon.gif");
if (icon.getIconWidth() == -1) {
JOptionPane.showMessageDialog(null,
"No image!", "Gahh!", JOptionPane.ERROR_MESSAGE);
} else {
label2.setIcon(icon);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.