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

时间:2011-08-05 16:04:08

标签: java swing jframe jlabel

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

// 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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

代码不仅每次都会生成新的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);
        }
    }
}