2017-05-04 122 views
1

我已經減少了我的代碼這樣一個簡單的功能:在窗口上顯示圖片。但是爲什麼這張照片沒有出現,但是我嘗試了?我創建了一個JFrame,然後創建了一個JPanel,它可以顯示圖片。然後將面板添加到框架。順便說一下,我導入了圖片並雙擊它以獲取網址。圖像沒有在窗口上顯示

import java.awt.*; 

import javax.swing.*; 

import com.sun.prism.Graphics; 

public class GUI { 
    JFrame frame=new JFrame("My game"); 
    JPanel gamePanel=new JPanel(); 

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

    public void go(){ 

     frame.setSize(300, 400); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     Background backPic=new Background(); 
     backPic.setVisible(true); 
     frame.getContentPane().add(backPic);   

     JPanel contentPane=(JPanel) frame.getContentPane(); 
     contentPane.setOpaque(false); 

     frame.setVisible(true); 
     } 

    class Background extends JPanel{ 
      public void paintComponent(Graphics g){ 
       ImageIcon backgroundIcon=new   ImageIcon("file:///E:/eclipse/EL/backgroundPicture.jpg"); 
       Image backgroundPic=backgroundIcon.getImage(); 

       Graphics2D g2D=(Graphics2D) g; 
       g2D.drawImage(backgroundPic,0,0,this); 
      } 
     } 
} 

回答

2

這是因爲您導入了com.sun.prism.Graphics。它應該是java.awt.Graphics

我也擺脫了路徑中的「file:///」位。而且你也可能不想在每個繪畫事件中加載圖像。這裏有一個更好的版本背景類; -

class Background extends JPanel { 

    Image backgroundPic; 

    public Background() { 
     ImageIcon backgroundIcon=new ImageIcon("E:/eclipse/EL/backgroundPicture.jpg"); 
     backgroundPic=backgroundIcon.getImage(); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2D=(Graphics2D) g; 
     g2D.drawImage(backgroundPic,10,10,this); 
    } 
} 
+2

這意味着你提供了新的方法'paintComponent(com.sun.prism.Graphics)',而不是壓倒一切的paintComponent(java.awt.Graphics)。 –

+3

@DavidGilbert *「這意味着你正在提供一種新的方法」*應該在任何重寫的方法中指定'@ Override'的一個原因。在貨運列車到達之前,得到編譯器警告我們錯誤的軌道上,這很方便。 –

+0

這意味着我也必須導入圖片,對不對?如果我刪除了我導入的圖片,它不會再顯示。什麼是「super.paintComponent(g)」的功能? – EstellaGu