2013-12-23 106 views
-1

我有兩個類。類GUI延伸JFrame,並且應該在屏幕上顯示JPanel,這是延伸JPanel的類Surface。試圖以Java在屏幕上顯示圖像,不起作用

類Surface有一個paintComponent方法,它應該顯示一個圖像,但由於某種原因它不會顯示它。下面的代碼:

import javax.swing.*; 

public class GUI extends JFrame { 

    GUI(){ 
     initUI(); 
    } 

    public void initUI(){ 
     Surface s = new Surface(); 
     add(s); 
     pack(); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String[]args){ 
     GUI gui = new GUI(); 
     gui.setVisible(true); 
    } 

} 

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

public class Surface extends JPanel { 

    Image image; 
    ImageIcon ii; 

    public void paintComponent(Graphics g) { 

     super.paintComponent(g); 

     Graphics2D g2d = (Graphics2D) g; 

     ii = new ImageIcon("redsquare.png"); 
     image = ii.getImage(); 

     Dimension d = new Dimension(); 
     d.width = image.getWidth(null); 
     d.height = image.getHeight(null); 
     this.setPreferredSize(d); 

     g2d.drawImage(image,50,50,null); 

    } 

} 
+0

哪裏是你的PNG文件位於圖像位置問題?把它放到項目的根文件夾中。 –

+2

永遠不會在paintComponent中加載圖像(ii = new ImageIcon(「redsquare.png」);),爲這個對象創建一個局部變量 – mKorbel

+1

另外,這可以通過在50像素的JLabel中顯示圖像來實現'EmptyBorder'。 –

回答

2

在文件中的位置似乎問題,請嘗試下一個代碼從項目的資源越來越PNG:

ii = new ImageIcon(getClass().getResource("redsquare.png")); 

在同一個包,例如redsquare.png文件Surface類。

1

如果你使用像Eclipse或Netbeans的是IDE,使用這種相對路徑「redsquare.png」,你需要像直接在項目的根

ProjectRoot 
     redsquare.png 
     src 
     bin 

另外要,聽的@mKorbel

明智的話 「從未加載圖像內的paintComponent(II =新的ImageIcon(」 redsquare.png 「);),對於該對象創建局部變量」 - @ mKorbel

此外,對於嵌入式資源,您應該真的考慮@ alex2410的答案。你想加載班級的圖像。

0

可能與它似乎 嘗試用不同的圖像源運行

+0

我通常會說「這不是一個答案,但可能會做出很好的評論」。 OTOH在這個線程中已經被注意到了,並且只是噪聲。 –