简体   繁体   English

如何使用Java显示我的图片?

[英]How can I get my Image to be displayed using Java?

Well basically my image will not display, i'm almost certain it's my file path (‪" C:\\Users\\Alex\\Desktop\\card.png" is what the image properties say is the file path but unless i put double slashes it confuses them for escape sequences. ) If someone has the answer it will be much appreciated. 好吧,基本上我的图像不会显示,我几乎可以确定它是我的文件路径(‪“ C:\\ Users \\ Alex \\ Desktop \\ card.png”是图像属性所说的文件路径,但是除非我加双斜杠)。如果有人给出了答案,将不胜感激。 Here's my code: 这是我的代码:

import java.awt.*;
import javax.swing.*;
public class IDK extends JFrame {



public static void main(String args[]) {

    new IDK();


}

public IDK(){

        notsure();

        }
public void notsure(){


    setBounds(420,100,440,400);
    setTitle("Frame");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    JLabel label1 = new JLabel("Tell me something");
    JLabel image = new JLabel();
    label1.setText("New Text");
    JTextField text = new JTextField("Insert text",30);
    image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
    panel.add(label1,image);
    panel.add(text);
    add(panel);
    validate();
    panel.setBackground(Color.CYAN); 
    setVisible(true);

}

}

There is no problem with using "\\" so long as it's escaped, as you have done, if your prefer you can use / instead and on Windows the JRE will correct for it. 只要已将“ \\”转义(如您所愿),就没有问题,如果您愿意,可以使用/代替,并且在Windows上JRE会对其进行纠正。

How ever, you should be adding the image separately, for example... 但是,您应该分别添加image ,例如...

image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
panel.add(label1);
panel.add(image);

The way you are doing it now assumes that image is a layout constraint for label1 , which it isn't. 现在,您的操作方式假设imagelabel1的布局约束,而实际上不是。

You should try and avoid using absolute paths and learn to use relative paths and/or embed the resources within the application context, this makes it easier to locate these resources at runtime. 您应该尝试避免使用绝对路径,并学会使用相对路径和/或将资源嵌入应用程序上下文中,这样可以更轻松地在运行时定位这些资源。

Create a folder in your project and call it ie 'resources' and put your image in that folder. 在您的项目中创建一个文件夹,并将其命名为“ resources”,然后将图像放置在该文件夹中。 This will ensure that given image is on your classpath and can be easily accessed. 这将确保给定的图像在您的类路径上并且可以轻松访问。

Then you can just do : 然后,您可以执行以下操作:

new ImageIcon("resources/card.jgp")

Problem with accessing outside resources is that special characters needs to be escaped and also if you export the project and give it to someone else, he/she will not have the image required by software ;) 访问外部资源的问题是特殊字符需要转义,并且如果您导出项目并将其提供给其他人,他/她将没有软件所需的图像;)

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

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