简体   繁体   English

java - 不加载Swing图像

[英]java - Swing image not loading

Whenever I try to add this image all I get is a blank jFrame. 每当我尝试添加此图像时,我得到的是一个空白的jFrame。 I am hoping some one can tell me what I am doing wrong. 我希望有人可以告诉我我做错了什么。 Also I have done a system.out.println on the image and it is getting loaded. 我还在图像上做了一个system.out.println,它正在加载。

        BufferedImage myPicture = ImageIO.read(getClass().getResourceAsStream("image.jpg"));


        javax.swing.JLabel jLabel2 = new JLabel(new ImageIcon(myPicture));            
        jLabel1.add(jLabel2);
        jLabel1.repaint();
public class LabelJarSample {

  public static void main(String args[]) {
    String title = "JLabel Sample";
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container content = frame.getContentPane();
    content.setLayout(new GridLayout(2, 2));

    JLabel label1 = new JLabel("Text Label");
    content.add(label1);

    Image warnImage = ImageLoader.getImage(LabelJarSample.class, "Warn.gif");
    Icon warnIcon = new ImageIcon(warnImage);
    JLabel label2 = new JLabel(warnIcon);
    content.add(label2);

    JLabel label3 = new JLabel("Warning", warnIcon, JLabel.CENTER);
    content.add(label3);

    String htmlLabel = "<html><sup>HTML</sup> <sub><em>Label</em></sub><br>"
        + "<font color=\"#FF0080\"><u>Multi-line</u></font>";
    JLabel label4 = new JLabel(htmlLabel);
    content.add(label4);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}




final class ImageLoader {

  private ImageLoader() {
  }

  public static Image getImage(Class relativeClass, String filename) {
    Image returnValue = null;
    InputStream is = relativeClass.getResourceAsStream(filename);
    if (is != null) {
      BufferedInputStream bis = new BufferedInputStream(is);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        int ch;
        while ((ch = bis.read()) != -1) {
          baos.write(ch);
        }
        returnValue = Toolkit.getDefaultToolkit().createImage(
            baos.toByteArray());
      } catch (IOException exception) {
        System.err.println("Error loading: " + filename);
      }
    }
    return returnValue;
  }
}

ref:http://www.java2s.com/Code/Java/Swing-JFC/LabelwithImage.htm 裁判:HTTP://www.java2s.com/Code/Java/Swing-JFC/LabelwithImage.htm

note: also check the image location path is correct 注意:还要检查图像位置路径是否正确

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

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