有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重新加载同一标签中的图像(不创建任何新标签)

我有一个代码,将显示从本地客户端获得的图像。它在不同的时间得到不同的图像。因此,我希望在每次刷新时都在同一标签中逐个显示所有图像。 下面的代码将在每次接收对象时生成新标签。如何修改以获得所需的输出

// For each connection it will generate a new label.   

public void received(Connection connection, Object object) {
    if (object instanceof Picture) {

        Picture request = (Picture) object;
        try {
            System.out.println(request.buff.length);
            InputStream in = new ByteArrayInputStream(request.buff);
            BufferedImage image = ImageIO.read(in);
            JFrame frame = new JFrame("caption");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Dimension dimension = new Dimension(image.getWidth(), image.getHeight());

            JLabel label = new JLabel(new ImageIcon(image)); //displays image got from each connection
            JScrollPane pane = new JScrollPane(label, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            frame.getContentPane().add(pane);
            frame.setSize(dimension);
            frame.setVisible(true);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    代码不仅会每次生成新的JLabel,还会生成新的JFrame、新的JScrollPane等等

    将代码分为两种方法initreceiveinit只会在开始时执行,并会创建所有的“环绕”,而receive会更新图像

    基本示例:

    JFrame frame;
    JLabel label;
    JScrollPane pane;
    // ...  
    public void init() {
        frame = new JFrame("caption");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension dimension = new Dimension(someDefaultHeight, someDefaultWidth);
        label = new JLabel(); //displays image got from each connection
        JScrollPane pane = new JScrollPane(label, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.getContentPane().add(pane);
        frame.setSize(dimension);
        frame.setVisible(true);
    }
    
    
    public void received(Connection connection, Object object) {
        if (object instanceof Picture) {
            Picture request = (Picture) object;
            try {
                System.out.println(request.buff.length);
                InputStream in = new ByteArrayInputStream(request.buff);
                BufferedImage image = ImageIO.read(in);
                Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
                label.removeAll();
                label.setIcon(new ImageIcon(image));
                frame.setSize(dimension);
                label.revalidate();
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println(ex);
            }
        }
    }
    
  2. # 2 楼答案

    我想您可以使用相同的JLabel并在同一个实例上调用setIcon方法。您还应该重用相同的JFrameJScrollPane。 因此,您应该在一个单独的方法中初始化它们,并在收到新对象时只调用setIcon方法