简体   繁体   English

如何在JFrame中刷新图像?

[英]How refresh image in JFrame?

There is some server and I need to get image from it. 有一些服务器,我需要从中获取图像。 And this image updates sometimes. 并且此图像有时会更新。 And program need to get this image and show it on a screen always in fullscreen. 程序需要获取此图像并将其始终以全屏显示在屏幕上。 I wrote some code and it works fine if run it once. 我写了一些代码,如果运行一次就可以正常工作。 But I can't handle with updating image. 但是我无法处理图像更新。 I need to get image every XX minutes or seconds from server and show it on the screen. 我需要每隔XX分钟或每秒钟从服务器获取一次图像,并将其显示在屏幕上。 May be I need some refresh image function like - repaint(), but I don't know how use it right in this code. 可能我需要一些刷新图像功能,例如-repaint(),但我不知道如何在此代码中正确使用它。 I tried cycle - while and Thread.sleep() but it didn't work correctly because of creating many excessed objects... Help me please. 我尝试了cycle-while和Thread.sleep(),但是由于创建了许多多余的对象而无法正常工作...请帮助我。

public class MyParser {
public static void main(String[] args) throws IOException, InterruptedException {
            String urlStr = "http://192.168.11.111/images/SGBWebServerImage.bmp";
            JFrame frame = new JFrame();
            URL url = new URL(urlStr);
            BufferedImage image = resize(ImageIO.read(url), 320, 1920);
            ImageIcon icon = new ImageIcon(image);
            frame.add(new JLabel(icon));
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setBackground(Color.BLACK);
            frame.pack();
            frame.setVisible(true);
    }

private static BufferedImage resize(BufferedImage img, int height, int width) {
    Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g2d = resized.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return resized;
}

I need to get image every XX minutes or seconds from server and show it on the screen. 我需要每隔XX分钟或每秒钟从服务器获取一次图像,并将其显示在屏幕上。

Use a Swing Timer to schedule some activity. 使用Swing Timer安排一些活动。 Read the section from the Swing tutorial on How to Use Swing Timers for more information. 阅读Swing教程中有关如何使用Swing计时器的部分, 获取更多信息。

When the timer fires you will need to: 计时器启动时,您需要:

  1. get the image from the server 从服务器获取图像
  2. update the Icon of the JLabel 更新JLabel的图标

Which means you will need to restructure your code so you have a reference to the label. 这意味着您将需要重组代码,以便对标签进行引用。 So you need to get rid of all the static methods. 因此,您需要摆脱所有静态方法。

You can check out: No delay in GUI execution even after implementing sleep in a separate thread for an example. 您可以签出:例如, 即使在单独的线程中实现了睡眠之后,GUI执行也不会延迟 You will just need to replace the logic in the actionPerformed(...) method to get your image and update the Icon of the label. 您只需要替换actionPerformed(...)方法中的逻辑即可获取图像并更新标签的图标。

Check if this helps. 检查是否有帮助。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MyImage extends JPanel implements ActionListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    JLabel imageLabel;

    public MyImage() {

        ImageIcon icon = new ImageIcon("https://picsum.photos/200/300/?random");
        setLayout(new BorderLayout());
        imageLabel = new JLabel(icon);
        add(imageLabel, BorderLayout.CENTER);
        javax.swing.Timer timer = new javax.swing.Timer(1000, this);
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    String imageName = "https://picsum.photos/200/300/?random";
                    URL url = new URL(imageName);
                    ImageIcon icon = new ImageIcon(url);
                    icon.getImage().flush();
                    imageLabel.setIcon(icon);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("testimage reload");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MyImage());
        frame.setLocationByPlatform(true);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM