先贴代码:
代码1class MyPanel extends JPanel{
    private Image image;
    public MyPanel(){
        image=this.getToolkit().createImage("stone.jpg");
    }
    public void paintComponent(Graphics g){
        g.drawImage(image,0,0,getWidth(),getHeight(),this);
    }
}代码2class MyPanel extends JPanel{
    public MyPanel(){
        
    }
    public void paintComponent(Graphics g){
        Image image=this.getToolkit().createImage("stone.jpg");
        g.drawImage(image,0,0,getWidth(),getHeight(),this);
    }
}
省略其他代码,但保证代码1是可以成功画图的,所以应该不存在其他部分代码造成问题。提问:
(1) 为什么代码1可以画出图片 而代码2不能画出图片?
(2) paintComponent(Graphics g)函数为什么未经显式调用就可以执行?是谁调用了它?初学乍练,请多多指教。先谢过了~~

解决方案 »

  1.   

    paintComponent(Graphics g)方法是你重写的方法,是自动调用的!~
    得到image流也可以这样做:
    BufferedImage image = ImageIO.read(new File("stone.jpg"));
    然后 g.drawImage(image,0,0,getWidth(),getHeight(),this);
      

  2.   

    具体原因没弄明白, 猜的可能是Image image=this.getToolkit().createImage("stone.jpg");  这句create image的时候,需要去paint 这个jpanel, 所以就造成死循环了, 一直在call paintComponent这个方法,所以就没画出来。
      

  3.   

    用getImage 不要用createImage
    两者是有区别的Image java.awt.Toolkit.getImage(String filename)
    Returns an image which gets pixel data from the specified file, whose format can be either GIF, JPEG or PNG. The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image. Since the mechanism required to facilitate this sharing of Image objects may continue to hold onto images that are no longer in use for an indefinite period of time, developers are encouraged to implement their own caching of images by using the createImage variant wherever available. If the image data contained in the specified file changes, the Image object returned from this method may still contain stale information which was loaded from the file after a prior call. Previously loaded image data can be manually discarded by calling the flush method on the returned Image. This method first checks if there is a security manager installed. If so, the method calls the security manager's checkRead method with the file specified to ensure that the access to the image is allowed.Image java.awt.Toolkit.createImage(String filename)
    Returns an image which gets pixel data from the specified file. The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant. This method first checks if there is a security manager installed. If so, the method calls the security manager's checkRead method with the specified file to ensure that the image creation is allowed.
      

  4.   

    4楼说的有道理,createImage()会创建新对象,调用paintComponent方法。死循环了
      

  5.   


    那请问createImage(),只是创建一个Image对象,为什么会调用JPanel的paintComponent()方法?