2012-05-31 81 views
2

我只是想知道爲什麼這個100x100 px .gif圖像沒有出現在屏幕上。該圖像位於相同的目錄中,因此程序找到它應該沒有問題。有人知道如何解決這個問題嗎?JFrame中的圖像顯示

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

public class Window extends JFrame{ 
//the pictures 
ImageIcon guy = new ImageIcon("tester.gif"); 
JLabel pn = new JLabel(guy); 
JPanel panel = new JPanel(); 

Window(){ 
    super("Photuris Lucicrescens"); 

    //Important 
    setSize(700,600); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    add(panel); 
    setVisible(true); 
    //Decoration 
    Image customIcon = Toolkit.getDefaultToolkit().getImage("iconImage.gif"); 
    setIconImage(customIcon); 
    //Adding the image 
    add(pn); 
} 
} 
+0

*「this 100x100 px .gif image」*您所指的是兩個GIF圖像中的哪一個?修剪第二個來源。你在使用IDE嗎? –

+0

我使用tester.gif,iconImage.gif只是爲了裝飾標題! –

回答

2

我在我的電腦上嘗試它,圖像顯示在圖標上。如果你想要在後臺展示圖片,請試試這個:

import java.awt.Image; 
import java.awt.Toolkit; 
import javax.swing.*; 

     public class Caine extends JFrame{ 
     //the pictures 
     ImageIcon guy = new ImageIcon("tester.gif"); 
     JLabel pn = new JLabel(guy); 
     JPanel panel = new JPanel(); 

     Caine(){ 
      super("Photuris Lucicrescens"); 

      //Important 
      setSize(700,600); 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      add(panel); 
      setVisible(true); 
      JLabel im = new JLabel(new ImageIcon("iconImage.gif")); 
      setIconImage(customIcon); 
      panel.add(im); 
      add(pn); 
     } 
     } 
+3

setVisible必須是最後的代碼行 – mKorbel

+0

我不知道你把「setVisible()」放在哪裏很重要! 它工作正常後!謝謝你的幫助! :) –

4

問題是你添加了兩個組件到JFrame。將組件添加到JFrame時,實際上會將其添加到其內容窗格中。默認情況下,內容窗格使用BorderLayout作爲其LayoutManager。如果您未設置約束,則認爲該組件位於中心。因此,這裏有兩個位於中心的組件,它們從LayoutManager接收相同的邊界,導致只顯示一個組件,另一個組件被隱藏。這就是爲什麼你看到JPanel而不是JLabel。

如果您想查看JLabel,請不要將該面板添加到框架。

其他說明:您已經創建了組件層次後

  • 調用setVisible()被調用。