2017-05-04 152 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