下面是一个简单的JavaFX聊天应用程序的实现。
- 创建项目并添加依赖
首先创建一个新的JavaFX项目。在pom.xml文件中添加以下依赖项:
<dependencies><dependency><groupId>org.openjfx</groupId><artifactId>javafx-controls</artifactId><version>16</version></dependency><dependency><groupId>org.openjfx</groupId><artifactId>javafx-fxml</artifactId><version>16</version></dependency><dependency><groupId>org.ow2.asm</groupId><artifactId>asm</artifactId><version>9.1</version></dependency>
</dependencies>
- 创建UI
创建UI需要两个窗口。一个是主聊天窗口,另一个是登录窗口。在/src/main/resources目录下创建两个FXML文件,分别命名为Chat.fxml和Login.fxml。
Chat.fxml:
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.text.Text?><VBox spacing="10.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1"><Text fx:id="title" text="Chat" style="-fx-font-size: 36; -fx-font-weight: bold" /><ListView fx:id="listView" style="-fx-font-size: 16" /><HBox spacing="10.0"><TextField fx:id="messageInput" promptText="Type Message Here" style="-fx-font-size: 16" /><Button fx:id="sendButton" text="Send" style="-fx-font-size: 16; -fx-background-color: #009688; -fx-text-fill: white" /></HBox>
</VBox>
Login.fxml:
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.text.Text?><VBox spacing="10.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1"><Text fx:id="title" text="Login" style="-fx-font-size: 36; -fx-font-weight: bold" /><TextField fx:id="usernameInput" promptText="Username" style="-fx-font-size: 16" /><HBox spacing="10.0"><PasswordField fx:id="passwordInput" promptText="Password" style="-fx-font-size: 16" /><Button fx:id="loginButton" text="Login" style="-fx-font-size: 16; -fx-background-color: #009688; -fx-text-fill: white" /></HBox><Text fx:id="loginError" text="" style="-fx-font-size: 16; -fx-text-fill: red" />
</VBox>
- 创建Controller
在/src/main/java目录下创建两个Controller类,ChatController和LoginController,分别对应Chat.fxml和Login.fxml。
ChatController:
public class ChatController implements Initializable {@FXMLprivate Text title;@FXMLprivate ListView<String> listView;@FXMLprivate TextField messageInput;@FXMLprivate Button sendButton;private String username;private Socket socket;private DataOutputStream outputStream;private DataInputStream inputStream;public void setUsername(String username) {this.username = username;title.setText("Chat - " + username);}public void initialize(URL location, ResourceBundle resources) {try {socket = new Socket("localhost", 8000);outputStream = new DataOutputStream(socket.getOutputStream());inputStream = new DataInputStream(socket.getInputStream());new Thread(() -> {while (true) {try {String message = inputStream.readUTF();Platform.runLater(() -> listView.getItems().add(message));} catch (IOException e) {e.printStackTrace();}}}).start();sendButton.setOnAction(event -> {try {String message = username + ": " + messageInput.getText();outputStream.writeUTF(message);outputStream.flush();listView.getItems().add(message);messageInput.setText("");} catch (IOException e) {e.printStackTrace();}});} catch (IOException e) {e.printStackTrace();}}public void disconnect() {try {socket.close();outputStream.close();inputStream.close();} catch (IOException e) {e.printStackTrace();}}}
LoginController:
public class LoginController {@FXMLprivate Text title;@FXMLprivate TextField usernameInput;@FXMLprivate PasswordField passwordInput;@FXMLprivate Button loginButton;@FXMLprivate Text loginError;private ChatController chatController;public void setChatController(ChatController chatController) {this.chatController = chatController;}public void initialize() {loginButton.setOnAction(event -> {String username = usernameInput.getText();String password = passwordInput.getText();if (authenticate(username, password)) {chatController.setUsername(username);showChat();} else {loginError.setText("Invalid username or password.");}});}private boolean authenticate(String username, String password) {// Authenticate username and password}private void showChat() {try {FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Chat.fxml"));Parent root = fxmlLoader.load();ChatController controller = fxmlLoader.getController();controller.setUsername(usernameInput.getText());Scene scene = new Scene(root);Stage stage = (Stage) loginButton.getScene().getWindow();stage.setScene(scene);stage.show();stage.setOnCloseRequest(event -> {controller.disconnect();});} catch (IOException e) {e.printStackTrace();}}}
- 运行应用程序
在主函数中启动应用程序。首先打开登录窗口,然后在登录成功后打开聊天窗口。
public class ChatApplication extends Application {public void start(Stage primaryStage) throws Exception {FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Login.fxml"));Parent root = fxmlLoader.load();LoginController controller = fxmlLoader.getController();ChatController chatController = new ChatController();controller.setChatController(chatController);Scene scene = new Scene(root);primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {launch(args);}}
现在应用程序已经完成了!运行ChatApplication类,然后在登录窗口中输入用户名和密码,就可以进入聊天窗口了。在聊天窗口中,输入消息并按下“发送”按钮,其他人将能够看到您的消息。