search
HomeJavajavaTutorialHow to use JavaFX and WebSockets in Java 9 to implement a graphical interface for real-time communication

How to use JavaFX and WebSockets to implement a graphical interface for real-time communication in Java 9

Introduction:
In today's Internet era, real-time communication is one of the very important functions. For example, real-time updates of stock market conditions, real-time chat, etc. This article will introduce how to use JavaFX and WebSockets in Java 9 to implement a graphical interface for real-time communication.

Part One: Introduction to JavaFX
JavaFX is a Java library for building rich client applications. It provides a powerful graphical interface to easily create various visual effects.

Part 2: Introduction to WebSockets
WebSockets is a technology used for real-time two-way communication between clients and servers. It allows servers to proactively send messages to clients and provides a simple protocol to handle real-time communication.

Part 3: Combination of JavaFX and WebSockets
Now let us take a look at how to combine JavaFX and WebSockets to achieve a graphical interface for real-time communication. First, we need to create a JavaFX application and add the WebSockets library to the project's dependencies.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class RealTimeApplication extends Application {

    private Session session;
    private TextArea messageArea;

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Real Time Application");

        VBox vbox = new VBox();

        messageArea = new TextArea();
        messageArea.setEditable(false);

        TextField inputField = new TextField();
        inputField.setOnAction(event -> {
            String message = inputField.getText();
            session.getAsyncRemote().sendText(message);
            inputField.setText("");
        });

        vbox.getChildren().addAll(messageArea, inputField);

        primaryStage.setScene(new Scene(vbox, 400, 300));
        primaryStage.show();

        connect();
    }

    @Override
    public void stop() {
        try {
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        messageArea.appendText(message + "
");
    }

    private void connect() {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            session = container.connectToServer(this, new URI("ws://localhost:8080/ws"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the above code, we created a JavaFX application named "RealTimeApplication" and added a TextArea for displaying messages and a TextField for inputting messages. When the user presses the Enter key in the TextField, we use the WebSockets session to send a message to the server. When a message is received from the server, we will display it in the TextArea.

Part 4: Server Side Setup
Next, we need to set up the server side to handle messages from clients and broadcast them to all connected clients. Here, we use Spring Boot to create a simple WebSockets server.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    @EnableWebSocketMessageBroker
    public static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

        @Override
        public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
            registration.setMessageSizeLimit(1024000);
        }

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws").withSockJS();
        }
    }

    @ServerEndpoint(value = "/ws")
    public static class WebSocketServer {

        @OnMessage
        public void onMessage(Session session, String message) throws IOException, EncodeException {
            for (Session client : session.getOpenSessions()) {
                client.getBasicRemote().sendText(message);
            }
        }
    }
}

In the above code, we create a WebSocket server named "WebSocketServer" and bind it to the "/ws" endpoint using the @ServerEndpoint annotation. When a message is received from a client, the server broadcasts it to all connected clients.

Conclusion:
By combining JavaFX and WebSockets, we can easily implement a graphical interface for real-time communication. Whether you're looking for real-time stock market updates or live chat, this technology can be extremely useful. I hope this article has been helpful to you in implementing a graphical interface for real-time communication using JavaFX and WebSockets in Java 9.

Reference link:

  • JavaFX official documentation: https://openjfx.io/javadoc/12/
  • WebSocket official documentation: https://www. w3.org/TR/websockets/
  • Spring Boot official documentation: https://spring.io/projects/spring-boot

The above is the detailed content of How to use JavaFX and WebSockets in Java 9 to implement a graphical interface for real-time communication. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to add complex borders to Excel cells using GrapeCity Documents for Java library in Java?How to add complex borders to Excel cells using GrapeCity Documents for Java library in Java?Apr 19, 2025 pm 08:39 PM

Using POI library in Java to add borders to Excel files Many Java developers are using Apache...

How to use CompletableFuture to ensure the order consistency of batch interface request results?How to use CompletableFuture to ensure the order consistency of batch interface request results?Apr 19, 2025 pm 08:36 PM

Efficient processing of batch interface requests: Using CompletableFuture to ensure that concurrent calls to third-party interfaces can significantly improve efficiency when processing large amounts of data. �...

In JavaWeb applications, is it reasonable for Dao layer to cache all personnel entity classes?In JavaWeb applications, is it reasonable for Dao layer to cache all personnel entity classes?Apr 19, 2025 pm 08:33 PM

In JavaWeb applications, the feasibility of implementing entity-class caching in Dao layer When developing JavaWeb applications, performance optimization has always been the focus of developers. Either...

Which motorcycle and motorcycle system is better? Comparison of advantages and disadvantages between open Android system and closed self-developed systemWhich motorcycle and motorcycle system is better? Comparison of advantages and disadvantages between open Android system and closed self-developed systemApr 19, 2025 pm 08:30 PM

The current status of motorcycle and motorcycle systems and ecological development of motorcycle systems, as an important bridge connecting knights and vehicles, has developed rapidly in recent years. Many car friends...

How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?Apr 19, 2025 pm 08:27 PM

When using MyBatis-Plus or tk.mybatis...

How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?Apr 19, 2025 pm 08:24 PM

How to query personnel data through natural language processing? In modern data processing, how to efficiently query personnel data is a common and important requirement. ...

How to parse next-auth generated JWT token in Java and get information in it?How to parse next-auth generated JWT token in Java and get information in it?Apr 19, 2025 pm 08:21 PM

In processing next-auth generated JWT...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)