2016-11-24 130 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

嘗試也把你的框架相關的代碼進行到底。 我想這樣你會避免需要驗證它。