我正在尝试添加 emoji
当我的客户输入 时转到我的聊天程序:)
我正在尝试将其添加到 FXML
中 Controller 。当用户键入 :) 时,我使用以下代码片段进行了捕获:
if(chat.contains(":)")) {
...
}
我的聊天记录打印成
textarea
命名 taChat
taChat.appendText(chat + '\n');
任何帮助表示赞赏!
最佳答案
更好的方法是使用 TextFlow
而不是使用 TextArea。
好处 :
Text
被视为 TextFlow 的子项。它们可以单独添加和访问。 ImageView
可以直接添加到TextFlow
作为一个 child 。 一个支持笑脸的简单聊天窗口 :)
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class ChatWindowWithSmiley extends Application {
public void start(Stage primaryStage) {
TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(10));
textFlow.setLineSpacing(10);
TextField textField = new TextField();
Button button = new Button("Send");
button.setPrefWidth(70);
VBox container = new VBox();
container.getChildren().addAll(textFlow, new HBox(textField, button));
VBox.setVgrow(textFlow, Priority.ALWAYS);
// Textfield re-sizes according to VBox
textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));
// On Enter press
textField.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ENTER) {
button.fire();
}
});
button.setOnAction(e -> {
Text text;
if(textFlow.getChildren().size()==0){
text = new Text(textField.getText());
} else {
// Add new line if not the first child
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/16x16/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();
});
Scene scene = new Scene(container, 300, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
输出
对于
unicode
Emoji 支持,请访问 How to support Emojis
关于image - 如何在 JavaFX 的 TextArea 中将内嵌图像添加到字符串的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712808/