2014-09-19 83 views
0

因此每2秒就会覆盖文件image.png。我想要一个applet在浏览器中显示图像。它确实显示图像,但问题是图像文件在计算机上更新后,图像永远不会在小程序中更新。我究竟做错了什么?图像在刷新时不更新

import java.awt.*; 
import java.util.Timer; 
import java.util.TimerTask; 

import javax.swing.JApplet; 

public class ImageUpdate extends JApplet { 

    Image picture; 
    Timer timer = new Timer(); 
    int delay = 2000; //2 second 
    int period = 4000; //4 seconds 

    public void init() { 
    picture = getImage(getDocumentBase(),"image.png"); 

    timer.scheduleAtFixedRate(new TimerTask() { 
      public void run() { 

      repaint(); 

       System.out.println("image updated"); 
      } 
     }, delay, period);  
    } 

    public void paint(Graphics g) { 
     g.drawImage(picture, 0,0, this);  
    }   

    public void update(Graphics g) 
    { 
     super.paint(g); 

    } 
} 
+0

你的图像已经被加载到'init'方法的applet中。在'TimerTask.run'方法中放置'picture = getImage(getDocumentBase(),“image.png”);'' – 2014-09-19 23:38:14

+0

1-确保在执行自定义绘画之前清除“Graphics”上下文; 2-你没有以任何方式重新加载图像,那么它是如何知道它已被更改的。将原始内容加载到内存中以加快访问速度 – MadProgrammer 2014-09-20 02:17:18

+0

@ ug_ picture = getImage(getDocumentBase(),“image.png”);在timertask没有工作。 – jerhynsoen 2014-09-21 00:27:37

回答

0

放弃了对小程序,并在HTML和JavaScript做到了。它的工作方式非常好。谢谢安德鲁。我真的想让小程序工作,但是......无论如何。

<html> 

<head> 
<script language="JavaScript"><!-- 
    function refreshIt() { 
    if (!document.images) return; 
     var date = new Date(); 
    document.images['image'].src = 'http://localhost:8080/image.jpg?ts=' + date.getTime(); 
     setTimeout('refreshIt()',2000); // refresh every 2000ms 
} 
    //--></script> 
</head> 

<body onLoad=" setTimeout('refreshIt()',2000)"> 

<img src="http://localhost:8080/image.jpg" name="image"> 

</body> 

</html>