I’m having issues when displaying images on JFrame (never used it before and i’m getting confused)
When I display the first image it seems to work but then when new images reach the Client the image doesn’t change at all and idk why.
Also I was planning on making this like a clock, for the moment I’m using :
“img = ImageIO.read(new ByteArrayInputStream(deserializedObject.getData().get(7)));”
so it’s only reading the seconds image (format is HH:MM:SS, the “:” also have a image)
Can someone help me on how to fix this?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Cliente extends JFrame {
private BufferedImage img;
private JLabel picLabel;
private BufferedImage lastimg = null;
public Cliente() throws IOException, ClassNotFoundException {
String hostname = "127.0.0.1";
int port = 12345;
InetAddress address = InetAddress.getByName(hostname);
DatagramSocket socket = new DatagramSocket();
byte[] buffer = new byte[2048 * 15]; //temporary size for now since i know its enough for the images
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(request);
JFrame frame = new JFrame("Clock");
JPanel jPanel = new JPanel();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
picLabel = new JLabel();
jPanel.add(picLabel);
frame.add(jPanel);
frame.setVisible(true);
while (true) {
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
System.out.println("Resposta recevida");
ByteArrayInputStream bais = new ByteArrayInputStream(response.getData());
ObjectInputStream ois = new ObjectInputStream(bais);
PDU deserializedObject = (PDU) ois.readObject();
ois.close();
bais.close();
img = ImageIO.read(new ByteArrayInputStream(deserializedObject.getData().get(7)));
if (img.equals(lastimg)){ //Temporary just to check if image was the same as last one (its not)
System.out.println("Imagem repetida -----------------------------------------");
}
lastimg = img;
picLabel.setIcon(new ImageIcon(img));
jPanel.repaint();
frame.repaint();
}
}
public static void main(String[] args) {
try {
new Cliente();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I tried many options but nothing seems to work, maybe I’m overthinking it
Leonardo Martins is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.