JavaFX chat Application

1.9k views Asked by At

Im trying to build a Chat Program. i can do it when i use java awt package but with java fx i seem to be a bit confused. when you first build a java fx project all your methods even the public static void main(string args[]) is in there and there's a place where you Start the primaryStage of the coding...I have no problem coding the visual side of my program its just i dont know where i should setup the Network part of my program and where to put it when im done..

**CODE: This is Just a View**

Server extends Application{

public void start(Stage primaryStage){
//Where you setup the visual of your program
}

public static void main(String args[]){
launch(args); // Where the program will run
}

public void ServerConnection(){
//where i put the codes to setup my streams and SOCKET
}

The ServerConnection method contains other methods as well But all of those will go to the ServerConnectionMethod now My question is Where will i place my ServerConnection Method so that it will run along with the my primary Stage

Sorry for the long post..have a String ="potato";

2

There are 2 answers

2
Michael Berry On

If a JavaFX application is launched correctly, it won't use the main() method at all - you can remove it temporarily (as an experiment) and check, but chances are it's not serving any purpose other than for backwards compatibility. You certainly should not rely on the main method doing anything special in the case of an FX app; it should only call launch() and nothing else.

Instead, your main class should extend Application, and the JavaFX runtime will create an instance of it for you, create a primary stage, and call the start method providing you with a reference to that stage. From this method you can do anything you like, but bear in mind it is on the UI thread (so you should create an additional thread for any long running task, the same as you would in any other toolkit such as Swing.)

0
Anton Steenvoorden On

You could run this setupConnection method at the beginning of the start(Stage primaryStage) method. This way it will be executed before showing the stage. You could also just run both from the main method, but as berry120 said: You don't need to call the launch(args) method in the main, if it extends Application you're fine with just the start method.

When you are done, you could use a

stage.setOnCloseRequest(e -> {
//code to execute, something like socket.close();
});

And you could change the stage.show() to stage.showAndWait()