2013-08-06 66 views
0

我有以下代码。虽然它正确显示线条,矩形,椭圆形和字符串,但图像无法加载。图像是在正确的目录中,只是不知道为什么它不显示...在applet中显示图像

import java.awt.*; // for Graphics, Image, and Color classes 
import java.applet.Applet; 

public class GraphicsDemo extends Applet 
{ 

    public void paint (Graphics g) 
    { 
     Image image; 
     image = this.getImage(getDocumentBase(), "flower.jpg"); 

     // display smaller complete image in upper left corner of window 
     g.drawImage(image, 0, 0, 427, 284,  // destination topL, botR 
       0, 0, 640, 427, this);  // source topL, botR 

     // establish color of all lines to be drawn 
     g.setColor(Color.BLUE); 

     // draw rectangle around region to be expanded 
     g.drawRect(200, 60, 120, 120);   // topL, width & height 

     // draw lines between corners of rectangles 
     g.drawLine(200, 60, 240, 240);   // upper left 
     g.drawLine(320, 60, 600, 240);   // upper right 
     g.drawLine(200, 180, 240, 600);   // lower left 
     g.drawLine(320, 180, 600, 600);   // lower right 

     // display expanded part of original image 
     g.drawImage(image, 240, 240, 600, 600, // destination topL, botR 
       300, 90, 480, 270, this); // source topL, botR 

     // draw rectangle around expanded part of image 
     g.drawRect(240, 240, 360, 360);   // topL, width & height 

     // create BLUE colored oval and write name on it 
     g.fillOval(520, 380, 45, 30);   // topL, width & height 
     g.setColor(Color.WHITE);   // change color for text 
     g.drawString("Max", 530, 400);   // string & start position 

    } // end main 
} // end class GraphicsDemo 

回答

0

很可能图像不存在于文档库中。其余代码在功能上没问题。添加init方法如下:

public void init() { 
    System.out.println(getDocumentBase()); 
} 

并将图像复制到显示的位置。


一些相关的注意事项:

你错过了从paint

super.paint(g); 

而且该声明将建议把这一声明

image = this.getImage(getDocumentBase(), "flower.jpg"); 

到applet的init方法,以便图像每次都没有被加载e applet被绘。