2012-12-09 15 views
1

我試圖讓jpeg顯示在JFrame上,我注意到一些圖像文件可以工作,而另一些則不能。我使用的是Eclipse,我的所有圖像都在項目的根目錄中。當我運行調試器並且命中我的斷點時,它會將圖像上的imageheight和imagewidth報告爲-1,不會顯示圖像。它會在顯示的圖像上報告正確的值。ImageIcon方法不適用於所有圖像

起初我認爲它與圖像大小有關,但在mspaint中使用分辨率播放後,我意識到情況並非如此。

這裏是我到目前爲止的代碼:

import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.imageio.*; 
import java.io.File; 

public class icon { 

    public static void main(String[] args) { 
     constructVNCForm(); 
    } 

public static void constructVNCForm() { 
     //Vars for GUI and essential layout code 
     final JFrame frame = new JFrame("This should be on top"); 
     frame.setSize(800, 640); 
     Container content = frame.getContentPane(); 
     frame.setVisible(true); 

     //image code here: 
     ImageIcon image = new ImageIcon("trial4.jpg"); 
     //ABOVE WORKS 

     JLabel imageLabel = new JLabel(image); 
     FlowLayout flow = new FlowLayout(FlowLayout.CENTER); 
     //add the image to the frame 
     content.add(imageLabel); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     content.setLayout(flow); 
    } 
} 

有任何的你有沒有和任何ImageIcons問題?我所有的jpegs都是300x300以下的各種尺寸。我對Java很陌生,所以如果你對我的代碼有任何建議,請告知。

+0

當您嘗試使用'ImageIO'加載它們時會發生什麼?它比'ImageIcon'提供更多有用的反饋。如果字節很小(<100Kb),您也可以將其中一個問題圖像上傳到圖像共享網站並鏈接到它。 –

+4

您應該將'frame.setVisible(true)'作爲最後一個語句放在'constructVNCForm'中。 – Reimeus

+0

@Reimeus答案是正確的。 – vels4j

回答

2

經過幾種不同尺寸的圖像測試,以下工作正常。通常應該在末尾調用setVisible(true)方法。

public static void main(String[] args) { 

     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame frame = new JFrame("This should be on top"); 
       frame.setSize(800, 640); 
       ImageIcon image = new ImageIcon("someImage.jpg"); 
       JLabel imageLabel = new JLabel(image); 
       FlowLayout flow = new FlowLayout(FlowLayout.CENTER); 
       frame.getContentPane().add(imageLabel); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(flow); 
       frame.pack(); 
       frame.setVisible(true); 
      } 
     }); 
    } 
相關問題