JavaFx stage does not respond after button action

The following class starts the UDP listener:

public class Client extends Application { UdpListener udp = new UdpListener(); public static void main(String[] args) { Application.launch(); } @Override public void start(Stage stage) { HBox root = new HBox(); Button startListeningButton = new Button("START LISTEN"); Button stopListeningButton = new Button("STOP LISTEN"); Scene scene = new Scene(root); root.setSpacing(10); root.getChildren().addAll(startListeningButton, stopListeningButton); EventHandler<MouseEvent> handlerStartListen = event -> { try { udp.run(); }catch (Exception e) { e.printStackTrace(); } }; EventHandler<MouseEvent> handlerStopListen = event -> { // }; startListeningButton.addEventFilter(MOUSE_CLICKED, handlerStartListen); stopListeningButton.addEventFilter(MOUSE_CLICKED, handlerStopListen); stage.setScene(scene); stage.setTitle("SNIFFER"); stage.show(); stage.sizeToScene(); } 

Below is the UdpListener :

 public class UdpListener implements Runnable { private final Integer LIST_PORT = 30000; private final Integer UDP_SIZE = 1472; private DatagramSocket socket; private DatagramPacket receivingPacket; public void run() { try { socket = new DatagramSocket(LIST_PORT); doProcessing(); } catch (Exception e) { e.printStackTrace(); } } public void doProcessing() throws IOException { while (true) { String checkAsterix; String asterixPackData; byte buff[] = new byte[UDP_SIZE]; receivingPacket = new DatagramPacket(buff, buff.length); socket.receive(receivingPacket); buff = receivingPacket.getData(); asterixPackData = new Decode(buff).getHexString(); checkAsterix = asterixPackData.substring(0, Math.min(asterixPackData.length(), 2)); Integer i = Integer.decode("0x" + checkAsterix); switch (i) { case (48): new ShowMessage("TROVATO"); //new atxlib.... break; default: new ShowMessage("SCARTO"); break; } } } } 

UdpListener is another class that simply opens a socket to sniff all the data on port XXXX and decode it.

I can run UdpListener directly. But if I associate this beginning with the code above, the application appears to be stuck, even if it works .

when I move the mouse cursor on the scene, it changes to "loading". Average time activity monitor says "java not responding".

Any suggestions?

+5
source share
1 answer

You are blocking the user interface thread using an infinite loop. If you do this, the user interface will stop responding. You need to run such a long path from another thread:

replace

 try { udp.run(); }catch (Exception e) { e.printStackTrace(); } 

with

 new Thread(udp).start(); 

and use Platform.runLater to update ui from the new thread, if necessary.

+2
source

Source: https://habr.com/ru/post/1235554/


All Articles