【问题标题】:I can't get my icon to show up in my JLabel swing component我无法让我的图标显示在我的 JLabel 摆动组件中
【发布时间】:2010-07-11 16:19:06
【问题描述】:

下面是在 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. 似乎我在这里遗漏了一些简单的东西,但我不知道。我是否需要将图标放在应用程序的其他位置。

【问题讨论】:

    标签: java swing


    【解决方案1】:

    我认为下面的文章会更好地解释如何加载图像资源,然后我会:)

    http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/icon.html

    【讨论】:

      【解决方案2】:

      我将支持 @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);
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-21
        • 2014-12-19
        • 1970-01-01
        • 2016-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 1970-01-01
        相关资源
        最近更新 更多