如何在GUI中刷新Web源图像

时间:2013-12-08 07:54:48

标签: java image swing user-interface web

我在Java中创建了一个简单的GUI应用程序,它在不同的部分显示来自Web的某些图像。

我遇到的麻烦是在一段时间(特别是40秒)后刷新图像。我需要应用程序再次从Web获取图像,并将其放置在三个JPanel之一中,只要应用程序正在运行,就会每40秒一次。

这是用于在应用程序启动时显示图像的代码:

try {
    BufferedImage cameraOne = ImageIO.read(new URL("IMAGE LINK HERE"));
    BufferedImage cameraTwo = ImageIO.read(new URL("IMAGE LINK HERE"));
    BufferedImage cameraThree = ImageIO.read(new URL("IMAGE LINK HERE"));

    cPanel1 = new CameraPanel(new ImageIcon(cameraOne).getImage());
    cPanel2 = new CameraPanel(new ImageIcon(cameraTwo).getImage());
    cPanel3 = new CameraPanel(new ImageIcon(cameraThree).getImage());
} catch (MalformedURLException ex) {
    throw new Error("One of the cameras you are trying to connect to doesn't exist!");
} catch (IOException ex) {
    throw new Error("CCTV couldn't connect to the required camera feeds!");
}

这是我用来尝试安排图像刷新的代码:

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

final Runnable refreshTask = new Runnable() {
    public void run() {

        // I need help here
    }
};

final ScheduledFuture<?> refreshHandler = scheduler.scheduleAtFixedRate(refreshTask, 10, 40, TimeUnit.SECONDS);

这是CameraPanel类,如用于在应用程序启动时显示图像的代码中所示:

class CameraPanel extends JPanel {
   private Image img;

    public CameraPanel(BufferedImage cameraImage) {
        this(new ImageIcon(cameraImage).getImage());
    }

    public CameraPanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}

任何解决方案?感谢。

我创建的完整课程可以在http://pastebin.com/nRNHHkfx

找到

0 个答案:

没有答案