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);
}
}
}
# 1 楼答案
代码不仅会每次生成新的
JLabel
,还会生成新的JFrame
、新的JScrollPane
等等将代码分为两种方法
init
和receive
init
只会在开始时执行,并会创建所有的“环绕”,而receive
会更新图像基本示例:
# 2 楼答案
我想您可以使用相同的
JLabel
并在同一个实例上调用setIcon
方法。您还应该重用相同的JFrame
和JScrollPane
。 因此,您应该在一个单独的方法中初始化它们,并在收到新对象时只调用setIcon
方法