下面是用于在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 驻留在一个文件夹中 - 即; images / myIcon.gif。好像我在这里遗漏了一些简单的东西,但我不知道。我是否需要将图标放在应用程序的其他位置。
答案 0 :(得分:1)
我认为以下文章将更好地解释如何加载图像资源然后我会:)
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/icon.html
答案 1 :(得分:0)
我将第二个@ 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);
}