2012-09-22 49 views
1

每当我尝试添加此图像时,我所得到的只是一个空白的jFrame。我希望有人能告诉我我做错了什么。另外我还在图像上做了一个system.out.println,它正在被加载。java - Swing image not loading

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


     javax.swing.JLabel jLabel2 = new JLabel(new ImageIcon(myPicture));    
     jLabel1.add(jLabel2); 
     jLabel1.repaint(); 
+3

希望这[回答](http://stackoverflow.com/a/9866659/1057230)可以帮助你在这条道路上:-)与此[答案](http://stackoverflow.com/a/11372350/ 1057230)!!!!虽然这是什么** jLabel1 ** thingy? –

+0

它的一个javax.swing.JLabel –

+0

@maxinfet我thu安德鲁的问什么是需要添加一个标签到另一个... – MadProgrammer

回答

4
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; 
    } 
} 

参考:HTTP://www.java2s.com/Code/Java/Swing-JFC/LabelwithImage.htm

注:也检查图像的位置路径是正确的

+1

什么是'ImageLoader'? – MadProgrammer

+2

其最后一个类在代码块下方滚动。尝试引用网址。 –

+0

对不起,我的坏:P – MadProgrammer