简体   繁体   English

如何将图像添加到GUI

[英]How to add an image to a GUI

I want to add a picture to my GUI, but it doesn't seem to be able to display the picture. 我想在我的GUI中添加一张图片,但它似乎无法显示图片。 (Maybe it can't find it?) I get no errors, all that happens is a blank JFrame pops up. (也许它找不到它?)我没有错误,所有发生的事情都是弹出一个空白的JFrame。 I'm using Eclipse, and the picture is in the same package I'm working in. 我正在使用Eclipse,图片在我正在使用的相同包中。

Code: 码:

package josh_package;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import java.awt.Image;
import javax.imageio.ImageIO;


public abstract class TrevCard extends JPanel implements ActionListener{

public static void main(String[] args)
{
    JFrame f = new JFrame("Here's Your Card!");
    JLabel label = new JLabel();  
    label.setIcon(new ImageIcon("Ace.png"));

     f.add(label);
     f.setLocationRelativeTo(null);
     f.setSize(600, 300);
     f.setVisible(true);

System.out.println("This is a program for cards!");
PlayingCard MyCard;
    MyCard = new PlayingCard(5,2);

    System.out.println(MyCard.GetValue());
    System.out.println(MyCard.GetSuit());

}

}

The ImageIcon constructor you're using takes a file name as argument. 您正在使用的ImageIcon构造函数将文件名作为参数。 This constructor thus tries to find this file on the disk, in the current directory (since the path you passed is a relative path). 因此,此构造函数尝试在当前目录中的磁盘上查找此文件(因为您传递的路径是相对路径)。 The current directory is not the directory where the Java source file is. 当前目录不是Java源文件所在的目录。 It's the directory from which the java command used to execute your app is launched. 它是用于执行应用程序的java命令的目录。

You don't want to use file IO to load your image. 您不希望使用文件IO来加载图像。 Instead, you want this image to be loaded from the classpath (ultimately, from inside the jar containing your packaged application). 相反,您希望从类路径加载此图像(最终,从包含打包应用程序的jar内部)。

To do that, use the constructor taking a URL as argument , and pass the URL of the resource: 为此,使用构造函数将URL作为参数 ,并传递资源的URL:

new ImageIcon(TrevCard.class.getResource("Ace.png"));

(provided Ace.png is in the same package as the TrevCard class) (提供的Ace.png与TrevCard类在同一个包中)

Instead of 代替

label.setIcon(new ImageIcon("Ace.png"));

Use: 采用:

java.net.URL imgURL = TrevCard.class.getResource("Ace.png");
label.setIcon(new ImageIcon(imgURL));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM