如何使用此代码添加图像?

时间:2018-03-27 10:23:08

标签: java

import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.Image;

import javax.sound.midi.Patch;

import javax.swing.*;

这是代码开始

public class graficCar extends JComponent
{
    private ImageIcon image1=null;

private JLabel label1=null;

private ImageIcon image2=null;

private JLabel label2=null;

 graficCar(){

setLayout(new FlowLayout());

此处的问题

image1=new ImageIcon(getClass().getResource("4596067.png"));

   label1=new JLabel(image1);
add(label1);
}

主要

public static void main(String[] args)
{
    graficCar g=new graficCar();
    g.setDebugGraphicsOptions(JFrame.EXIT_ON_CLOSE);
    g.setVisible(true);

}

1 个答案:

答案 0 :(得分:0)

正如您所提到的,您的png文件位于C:\Users\user\Downloads文件夹中。我打赌课程在其他地方。 问题是getResource()默认情况下在类路径中查找文件。 Here如果你想深入了解,你可以找到详细信息。

一种解决方案是将.png放在.java类的旁边,但这是不好的做法。更方便的方式描述here。最佳做法是为项目中的资源创建特殊文件夹,然后使用相对路径。如何做到这一点超出了范围,尽管它在许多站点和Stackoverflow中都有描述。不要犹豫使用搜索:)

相关问题