IAmBlake IAmBlake - 10 days ago 7
Java Question

How to add text in the window in javaFX?

My program sends a message to the server which is shown in a window and receives a message from a window which is also added in the window of client.

But my program doesn't show the message received from the server though i added:

textFlow.getChildren().add(text);
in accept thread.

What should i do?

public class NewClient extends Application {

Thread send;
Thread accept;

DatagramPacket pack;
DatagramSocket sock;
private List<String> str;
String name , sname;
int listeningPort;
InetAddress server_ip;

String sender;
ScrollPane sp = new ScrollPane();
TextFlow textFlow = new TextFlow();
TextField userTextField = new TextField();
TextField fTextField = new TextField();

private String message;
private String recip = null;
Button button = new Button("Send");

volatile boolean st = false;
Stage theStage;

public Scene Chat_Box() {

TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(10));
textFlow.setLineSpacing(10);
TextField textField = new TextField();
textField.setPrefSize(50, 30);
Button button = new Button("Send");
button.setPrefSize(80, 30);
VBox container = new VBox();
VBox box = new VBox();
box.getChildren().addAll(sp, textFlow);
container.setPadding(new Insets(10));
container.getChildren().addAll(box, new HBox(textField, button));
VBox.setVgrow(sp, Priority.ALWAYS);
VBox.setVgrow(textFlow, Priority.ALWAYS);

textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));

textField.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.ENTER) {
button.fire();
}
});
button.setOnAction(e -> {
st = true;
Text text;
if (textFlow.getChildren().size() == 0) {
text = new Text(textField.getText());
message = textField.getText();
System.out.println(message);
} else {
message = textField.getText();
text = new Text("\n" + textField.getText());
}
if (textField.getText().contains(":)")) {
ImageView imageView = new ImageView(
"http://files.softicons.com/download/web-icons/network-and-security-icons-by-artistsvalley/png/32x32/Regular/Friend%20Smiley.png");
// Remove :) from text
text.setText(text.getText().replace(":)", " "));
textFlow.getChildren().addAll(text, imageView);
} else {
textFlow.getChildren().add(text);
}
textField.clear();
textField.requestFocus();
});
VBox vb = new VBox();
vb.getChildren().addAll(textFlow);
sp.setVmax(440);
sp.setPrefSize(400, 300);
sp.setContent(vb);
sp.vvalueProperty().bind((ObservableValue<? extends Number>) vb.heightProperty());
Scene scene2 = new Scene(container, 400, 300);
return scene2;
}

public void start(Stage stage) throws IOException {
this.str = getParameters().getRaw();
name = str.get(0);
listeningPort = Integer.parseInt(str.get(1));
server_ip = InetAddress.getByName(str.get(2));
theStage = stage;
Scene scene = Chat_Box();
stage.setScene(scene);
stage.show();
send = new Thread() {

public void run() {
DatagramSocket sock = null;
try {
sock = new DatagramSocket();
} catch (SocketException ex) {
Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
InetAddress host = server_ip;
try {
if (st && ( message != null )) {
String in = message;
byte[] data = new byte[1024];
data = in.getBytes();
DatagramPacket sendPack = new DatagramPacket(data, data.length);
sendPack.setPort(5050);
sendPack.setAddress(host);
sock.send(sendPack);
st = false;
}
} catch (Exception e) {
System.out.println(e);
}
}
}

};
send.start();
accept = new Thread() {

public void run() {
try {
sock = new DatagramSocket(listeningPort);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
byte[] data = new byte[1024];
pack = new DatagramPacket(data, data.length);
try {
sock.receive(pack);
} catch (IOException e) {
e.printStackTrace();
}
String incoming = null;
try {
incoming = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Text text = new Text(incoming);
textFlow.getChildren().add(text);
}
}
};
accept.start();
}

public static void main(String[] args) throws IOException {
launch(args);
}

}

Answer

You should use:

Platform.runLater(()->{

 Text text = new Text(incoming);
 textFlow.getChildren().add(text);

});

The SceneGraph is not allowed to be changed from other Threads . Only JavaFX main Thread can modify the SceneGraph.

So calling this method you send this Runnable Object to a QUEUEand it will be called from the JavaFX Main Thread to modify the SceneGraph.


What is the SceneGraph?

The GUI in JavaFX is constructed as a scene graph. A scene graph is a collection of visual elements,called nodes, arranged in a hierarchical fashion. A scene graph is built using the public JavaFX API.


How events are managed in JavaFX?

In JavaFX,event queues are managed by a single, operating system–level thread called JavaFX Application Thread. All user input events are dispatched on the JavaFX Application Thread. JavaFX requires that a live scene graph must be modified only on the JavaFX Application Thread.