2016-11-24 131 views
-1

我是新来的挥杆,我试图显示,我用下面的代码拖进我的项目一个简单的图像。一切都编译并运行,但是,图像不显示。爪哇 - 秋千显示图像不工作

顺便说一下,我真的很喜欢这样做,而不是从文件路径中获取图像。

代码:

public static void main(String[] args) throws IOException { 
    // TODO Auto-generated method stub 

    ImageProcessorApp IPA = new ImageProcessorApp(); 
    IPA.displayImage(); 
} 

void displayImage() throws IOException { 
    JFrame frame = new JFrame("frame"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(500, 500); 
    frame.setVisible(true); 

    BufferedImage wPic = ImageIO.read(this.getClass().getResource("url-2.jpg")); 
    JLabel wIcon = new JLabel(new ImageIcon(wPic)); 
    frame.add(wIcon); 
    System.out.println("added image"); 

} 
+1

没有'this.getClass()的getResource( “URL-2.JPG”)'返回一个非空的对象?我的猜测是文件名/路径是错误的。你到底在哪条路径上拖动图像? – cello

+0

是类路径中的图像文件,所以getResource方法可以找到它?上看到类路径是:的System.out.println(System.getProperty( “java.class.path”)); – NormR

回答

0

首先,你必须调用方法.setVisible();只有在框架中添加了所有组件之后。 中学 - 你必须解决您的路径图像,只需添加图像在您的项目主类旁边。 这是工作的解决方案:

import javax.swing.*; 
    import java.io.IOException; 

    /** 
    * Created by Алексей on 24.11.2016. 
    */ 
public class Main { 

public static void main(String[] args) throws IOException { 

    displayImage(); 
} 

public static void displayImage() throws IOException { 
    JFrame frame = new JFrame("frame"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(500, 500); 

    JLabel imgLabel = new JLabel(new ImageIcon("src/url-2.jpg")); 

    frame.add(imgLabel); 

    frame.setVisible(true); 
} 
} 
0

尝试使用

frame.validate(); 

添加图像后,在其他情况下,框架将不会被更新! 如果这不起作用,请检查资源是否被找到!

工作版本:

void displayImage() throws IOException { 
     JFrame frame = new JFrame("frame"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(500, 500); 
     frame.setVisible(true); 

     BufferedImage wPic = ImageIO.read(ClassLoader.getSystemResource("img/url-2.jpg")); 
     JLabel wIcon = new JLabel(new ImageIcon(wPic)); 
     frame.add(wIcon); 
     frame.validate(); 
     System.out.println("added image"); 

    } 
0

尝试也把你的框架相关的代码进行到底。 我想这样你会避免需要验证它。