本文介绍了如何在JavaFX的TextArea中将内嵌图像添加到字符串的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我的客户输入时,我正在尝试将表情符号
添加到我的聊天程序中:)
我想在 FXML
控制器中添加它。我在用户输入:)时使用以下代码片段捕获:
if(聊天。包含(:))){
...
}
我的聊天打印到 textarea
名为 taChat
taChat.appendText(chat +'\ n');
感谢任何帮助!
解决方案
更好的方法是使用
I am trying to add an emoji
to my chat program when my client types :)
I am trying to add this in the FXML
controller. I have captured when the user types :) using the following code snippet :
if(chat.contains(":)")) {
...
}
My chat is printed into a textarea
named taChat
taChat.appendText(chat + '\n');
Any help is appreciated!
解决方案
A better approach would be to use TextFlow
instead of using TextArea.
Advantages :
- Individual
Text
are treated as children to the TextFlow. They can be added and accessed individually. ImageView
can be added directly to theTextFlow
as a child.
A simple chat window with support for smiley :)
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);
}
}
Output
For unicode
Emoji support, please visit How to support Emojis
这篇关于如何在JavaFX的TextArea中将内嵌图像添加到字符串的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!