Skip to content
Advertisement

Updating the JavaFx Gui with threads and or Tasks

I am creating a chat program that contains a GUI that I have created in the new version of the JavaFx Scene builder. I have a main method that extends application and i have a simpleController (that controls all the buttons, labels, anchorPanes, etc) in my GUI.

Other than that, I have a server application that can receive and send messages. For this purpose, I have created the following simple protocol:

Commands / Description:

  • 1 – Ask for permission to connect and at the same time, ask for a user ID (server finds out how many users are online and adds the id+1)
  • 2 – Chat, the client sends an ID and a String message (Example: 21
    Hello (note all of these are on a separate line))
  • 3 – Disconnects the client.
  • 4 – Shows a list of all the clients online.
  • 5 – Ask who else is online (this is only used when a user is connecting and he needs to know how many users are online in order to update the GUI).
  • 10 – Error of all sorts if the server returns the 10 message it means that the call the client just did was an error or that it could not
    be completed!

Using this simple logic, it should be fairly easy for me to make users connect, chat and disconnect. However, it turned out that what should have been a simple task has turned out to be my worst nightmare.

So far my users has no problem connecting to the program and more users can connect at the same time.

Where things start to get tricky is when I want to send and receive messages between server and client.

I do not know how I can update my GUI while using a thread. I have tried to read up on the Task class, but I am unable to see whether this should be used instead of a thread or the thread should have this as a parameter.

Should I create a new class that listens for input and make that class extend thread? OR
Should the thread be running in my simpleController class?

Main

JavaScript

simpleController

JavaScript

Client

JavaScript

I am really sorry about the code being kind of messy. The run() method in the simple controller was an attempt to make a thread of the simpleController. However, this did not work as I expected. 🙁

The main goal of this is basically to make sure that the two people in the chat room can chat together. So, all it has to do is update 1 or 2 textareas.

Advertisement

Answer

This is old but since it was up there in google I would like to point out your best bet is to use

JavaScript

or

Bean Properties like

JavaScript

Which are thread safe.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement