简体   繁体   English

使用 ImageIcon 和 JLabel

[英]Using an ImageIcon and a JLabel

My goal is to have an imageIcon and add it so a JLabel so it will appear on my GUI.我的目标是拥有一个 imageIcon 并将其添加为 JLabel,以便它出现在我的 GUI 上。 So far my code is:到目前为止,我的代码是:

package classes;

import javax.swing.*;

public class Picture extends JFrame {

    private ImageIcon _image1;
    private JLabel _mainLabel;      

    public Picture(){           
        _image1 = new ImageIcon("picture1.jpg");
        _mainLabel = new JLabel(_image1);
        add(_mainLabel);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }    
}    

package classes;

public class Driver {    
    public static void main(String[] args) {
        Picture p = new Picture();    
    }    
}

The problem is the picture does not appear on my GUI.问题是图片没有出现在我的 GUI 上。 If anyone has any suggestions please let me know thanks!如果有人有任何建议,请告诉我,谢谢!

Are you sure that Java is looking in the right location for your picture1.jpg file?您确定 Java 正在为您的图片 1.jpg 文件寻找正确的位置吗? Is this file located in the current working directory?该文件是否位于当前工作目录中?

Put this code somewhere in your program so that it gets called when the program is run:将此代码放在程序中的某个位置,以便在程序运行时调用它:

// show the current working directory
System.out.println("current working directory is: " + System.getProperty("user.dir")); 

The String returned will tell you where Java is looking, where your current working directory is located.返回的字符串将告诉您 Java 正在查找的位置,您当前的工作目录所在的位置。 You can then use that information to adjust your path or you could always just use the full path to the image file.然后,您可以使用该信息来调整您的路径,或者您始终可以只使用图像文件的完整路径。

Edit:编辑:
Also, don't forget to pack your JFrame so that it will layout the components and size itself accordingly:另外,不要忘记打包您的 JFrame 以便它会相应地布局组件和大小:

   public Picture() {

      _image1 = new ImageIcon(IMAGE);
      _mainLabel = new JLabel(_image1);
      add(_mainLabel);

      pack(); // to tell the layout managers to set up the GUI
      setLocationRelativeTo(null); // center things
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

For setting image to jlabel simple put one line code in your program:要将图像设置为 jlabel,只需在程序中放入一行代码:

yourlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("your image location here")));

we can set Jlabel with image and text also.我们也可以用图像和文本设置Jlabel

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

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