public class ConnectionData { @FXML //-- public TextArea receiveData; @FXML //-- public TextField sendData; @FXML //-- ( , bind sendDataProperty, ) public Button sendButton; // binding private StringProperty sendDataProperty = new SimpleStringProperty(""); // BlockingQueue<String> rxDataQueue = new LinkedBlockingQueue<>(); @FXML public void initialize() { sendData.textProperty().bindBidirectional(sendDataProperty); sendButton.disableProperty().bind(sendDataProperty.isEmpty()); Task<Void> task = new Task<Void>() { @Override public Void call() throws Exception { // , new MessageConsumer Platform.runLater(() -> new MessageConsumer(rxDataQueue, receiveData, rxDataQueue.size()).start()); return null; } }; new Thread(task).start(); } public class MessageConsumer extends AnimationTimer { private final BlockingQueue<String> messageQueue ; private final TextArea textArea ; private int messagesReceived = 0 ; public MessageConsumer(BlockingQueue<String> messageQueue, TextArea textArea, int numMessages) { this.messageQueue = messageQueue ; this.textArea = textArea ; } @Override public void handle(long now) { List<String> messages = new ArrayList<>(); messagesReceived += messageQueue.drainTo(messages); messages.forEach(msg -> textArea.appendText(msg)); } } public Button getPropertySendButton() { return sendButton; } public String getSendDataProperty() { String sendBuff = sendDataProperty.get(); sendDataProperty.set(""); return sendBuff; } public void clearReceiveData() { //-- flush receiveData.textProperty().setValue(""); } public void setReceiveData(byte[] buffer) { // try { rxDataQueue.add(new String(buffer, "UTF-8")); } catch (UnsupportedEncodingException ex) { System.err.print(ex); } } }
Source: https://habr.com/ru/post/354954/
All Articles