您好,我正在做的是我从客户端接收图像并在循环中显示它。数据被正确接收但是当循环结束时只显示最后接收的图像..
这不是主线控制器。我不知道它接收数据有什么不对,它应该在每次迭代时更新......
这是代码:
@FXML ImageView currentframe;
public void run()
{
System.out.println("hi controller");
System.out.println("creating socket");
DatagramSocket serverSocket=null;
try {
serverSocket = new DatagramSocket(1001);
} catch (SocketException ex) {
Logger.getLogger(threadclass.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("created socket");
byte[] receiveData = new byte[50000];
//byte[] sendData = new byte[1024];
//BufferedImage img = null;
//Image image = null;
int counter = 0;
while(counter<20){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
serverSocket.receive(receivePacket);
} catch (IOException ex) {
Logger.getLogger(threadclass.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("packetreceive");
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(receivePacket.getData()));
} catch (IOException ex) {
Logger.getLogger(threadclass.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("packetreceive1");
System.out.println("received packet length "+receivePacket.getLength());
Image image= SwingFXUtils.toFXImage(img, null);
Image tempImg = image;
Platform.runLater(() -> currentframe.setImage(tempImg));
/*
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(threadclass.class.getName()).log(Level.SEVERE, null, ex);
}*/
//currentframe.setImage(image);
//threadclass t = new threadclass(currentframe, image);
//t.start();
//Platform.runLater(null);
counter++;
System.out.println("IMAGE SET ON FRAME...");
}
//System.out.println("ssdcd" );
// currentframe.setImage(image);
//System.out.println("last packet ");
}
这是我在控制器中启动线程的方式:
@FXML
public void btn(ActionEvent event) throws IOException, InterruptedException
{
threadclass t = new threadclass(currentframe);
t.run();
}
答案 0 :(得分:1)
调用
t.run();
只需在当前线程(可能是FX Application线程)上调用run()
方法。要开始新线程,您需要调用
t.start();
假设threadclass
(sic)是Thread
的子类。