Java 将 ImageIcon 添加到 JLabel

问题描述 投票:0回答:4

我正在尝试用 Java 制作一个非常基本的游戏,但在

JFrame
上显示图像时遇到问题。它过去对我有用,但现在不行了,我看不出我做错了什么。

我尝试打印当前工作目录并更改获取图像的位置以匹配该目录。问题很可能是没有获取图像,因为我的(文件查找器或文件阅读器或类似的东西)可以毫无问题地找到它,但我无法正确地将其(

ImageIcon
)添加到
JLabel
,或者添加到
JFrame

这是我的代码...

JFrame frame = new JFrame("no image");
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(image);
frame.add(imagelabel);

JFrame
已经是
setVisible(true)
pack()

有人可以帮助我理解出了什么问题吗?

java swing jframe jpanel imageicon
4个回答
12
投票

你的问题就在这里:

   ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
   JLabel imagelabel = new JLabel(character);

您创建了一个 ImageIcon“图像”,但您使用“字符”创建了 JLabel。

应该是:

JLabel imagelabel = new JLabel(image);

2
投票

尝试一下,

ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);

看看教程 - 如何使用图标


0
投票

高潮mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm


-1
投票
import javax.awt.*; 
import java.awt.*; 
import java.awt.event*; 

//class name image 
class image { 
    image() 
    //constructor { 
        Frame f=new Frame("Image"); 
        //Frame
        f.setSize(500,500); 
        f.setVisible(true); 
        Panel p =new Panel(); 
        //Panel 
        f.add(p); 
        p.addLayout(null); 
        ImageIcon ii=new ImageIcon("set your image path"); 
        //ImageIcon is used to image Display . 
        Label l =new Label(ii); 
        p.add(ii); 
        p.setBounds(set you bounds); 
        //Like that(20,20,500,40); 
    } 

    public static void main(String [] args) { 
        image obj = new 
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.