我在哪里将我的图像放到Eclips上阅读?

时间:2017-08-14 04:23:43

标签: jlabel imageicon

我将在Eclips中运行以下应用程序,但它没有显示imageIcon。我将我的图像放在不同的文件夹中,但它确实有效。 我的程序没有出错,但只显示文本标签,而不是图片标签。 请你帮助我好吗 ? 提前谢谢。

package GUIpackage;

import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;

public class LabelDemo 
{
    public static void main( String[] args )
    {
        JLabel northLabel = new JLabel( "North" );
        ImageIcon labelIcon = new ImageIcon( "bug1.png" );
        JLabel centerLabel = new JLabel( labelIcon );
        JFrame application = new JFrame();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.add( northLabel, BorderLayout.NORTH );
        application.add( centerLabel, BorderLayout.CENTER );
        application.setSize( 300, 300 ); // set the size of the frame
        application.setVisible( true ); // show the frame
    }

}

1 个答案:

答案 0 :(得分:0)

只有在Eclipse中的不同文件夹中移动图像才会使图像无法访问。要检索图像,您需要使用ClassLoader编写加载器方法。

你所做的基本上是用NullPointer创建你的labelIcon,然后通过调用loader方法为它分配实际的ImageIcon:

ImageIcon labelIcon = null;
try {
    labelIcon = loadIcon("bug1.png");
} catch (Exception e) {
    // TODO: handle exception
}

我在代码上工作了一点,这将是一个有效的解决方案:

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class LabelDemo {

public static void main(String[] args) {
    LabelDemo ld = new LabelDemo();
}

public LabelDemo() {
    JLabel northLabel = new JLabel("North");
    ImageIcon labelIcon = null;
    try {
        labelIcon = loadIcon("bug1.png");
    } catch (Exception e) {
        // TODO: handle exception
    }
    JLabel centerLabel = new JLabel(labelIcon);
    JFrame application = new JFrame();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    application.add(northLabel, BorderLayout.NORTH);
    application.add(centerLabel, BorderLayout.CENTER);
    application.setSize(300, 300); // set the size of the frame
    application.setVisible(true); // show the frame
}

public ImageIcon loadIcon(String iconName) throws IOException {
    ClassLoader loader = this.getClass().getClassLoader();
    BufferedImage icon = ImageIO.read(loader.getResourceAsStream(iconName));
    return new ImageIcon(icon);
}
}

要使此代码正常工作,您需要将图像放入Eclipse中的src文件夹。

在您的示例中,您需要创建LabelDemo的实例,否则您将无法调用this.getClass().getClassLoader();,因为您无法在静态方法中使用this

希望我能帮到你

相关问题