I have a code that will show the image got from a local client. It gets different images in different time. Hence , i want to show all the images one by one in the same label refreshing each time.
The code below will generate new label each time the object is received. How can i modify so that i will get the output as i want?
// 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);
}
}
}
The code will not only generate new
JLabeleach time, but also newJFrame, newJScrollPaneetc…Separate the code into two methods
initandreceive.initwill be executed only at the beginning and will create all the “around” whilereceivewill update the image.Basic example: