2011-08-31 70 views
0

您好再次成員#1,Applet的圖像丟失

的CatchTheCreature Applet類應該顯示的圖像的重繪在由延時不同的位置,但由於某種原因沒有被顯示的圖像。

import java.awt.Color; 
    import java.awt.Graphics; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import java.awt.event.MouseEvent; 
    import java.awt.event.MouseListener; 
    import java.util.Random; 

    import javax.swing.ImageIcon; 
    import javax.swing.JApplet; 
    import javax.swing.Timer; 

    public class CatchTheCreature extends JApplet { 

private int height = 300; 
private int width = 600; 
private final int delay = 1001; 

private ImageIcon image; 
private Timer timer; 
private int x, y; 
private int counter = 0; 
Random gn = new Random(); 

public void init() { 
    DotListener dot = new DotListener(); 
    addMouseListener(dot); 

    image = new ImageIcon("Monster.png"); 

    timer = new Timer(delay, new timerListener()); 
    x = 40; 
    y = 40; 
    getContentPane().setBackground(Color.black); 

} 

// Action Listener Methods 
private class timerListener implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 

     x = gn.nextInt(width); 
     y = gn.nextInt(height); 

     repaint(); 
    } 

} 

private class DotListener implements MouseListener { 

    public void mousePressed(MouseEvent event) { 

    } 

    @Override 
    public void mouseClicked(MouseEvent event) { 
     if (event.getX() > (x) && event.getX() < (x + 60) 
       && event.getY() < (y + 60) && event.getY() > (y)) { 
      x = gn.nextInt(width); 
      y = gn.nextInt(height); 
      counter = counter + 1; 
      repaint(); 
     } 
    } 

    @Override 
    public void mouseEntered(MouseEvent event) { 

    } 

    @Override 
    public void mouseExited(MouseEvent event) { 

    } 

    @Override 
    public void mouseReleased(MouseEvent event) { 

    } 

} 

public void paint(Graphics g) { 
    super.paint(g); 
    g.setColor(Color.yellow); 
    image.paintIcon(this, g, x, y); 
    g.drawString("Clicked accuratly: " + counter, 5, 15); 
} 

public void start() { 
    timer.start(); 

} 

public void stop() { 
    timer.stop(); 
} 

}

這是我的html文件

 <applet code = CatchTheCreature width = 250 height = 300> 

    </applet> 

如果有人能告訴我怎樣可以顯示小程序上的圖片圖標我將非常感激。

由於

回答

1

..image =新的ImageIcon( 「Monster.png」);

  • String基於構造函數ImageIcon假定的String來表示File
  • 沙盒小程序無法訪問File對象,但可以訪問來自相同代碼庫/文檔庫的URL
  • 使用getDocumentBase()/getCodeBase()與圖像的相對路徑,並且applet將是可移植的(假設圖像也被上傳到相同的地方)。