I'm trying to make a chatBox with javafx, and I want the messages from the client to be aligned to right and the rest to left.
I'm using a Vbox
, wrapped in a Scrollpane
and in that Vbox, each message is wrapped in another Vbox.
But aligning the inner Vbox doesn't work.
Here is my code:
private VBox addMsg(String senderName, String text, String time) {
Label snderName = new Label(senderName + ":");
snderName.setId("senderName");
snderName.setMaxWidth(400);
snderName.setAlignment(Pos.BASELINE_LEFT);
Label msgText = new Label(text);
msgText.setId("msgText");
msgText.setWrapText(true);
msgText.setMaxWidth(400);
Label msgTime = new Label(time);
msgTime.setId("msgTime");
msgTime.setMaxWidth(400);
msgTime.setAlignment(Pos.BASELINE_RIGHT);
VBox msg = new VBox(snderName, msgText, msgTime);
msg.setBackground(new Background(new BackgroundFill(Color.AQUA, new CornerRadii(3d), Insets.EMPTY)));
msg.setPadding(new Insets(5));
msg.setMaxWidth(400);
msg.setEffect(new DropShadow(2, Color.DARKBLUE));
return msg;
}
public void buildChatBox() {
Button backToPublicChat = new Button("<");
backToPublicChat.setId("backToPublicChat");
backToPublicChat.setVisible(false);
Text chatWindowInfo = new Text("public chat room");
chatWindowInfo.setId("chatWindowInfo");
VBox chatHistory = new VBox();
chatHistory.setId("chatHistory");
chatHistory.setPrefWidth(CHAT_BOX_WIDTH);
chatHistory.setPrefHeight(GAME_HEIGHT - 50);//badsmell
TextField messageField = new TextField("type your message...");
messageField.setId("messageField");
messageField.setPrefHeight(30);
messageField.setPrefWidth(CHAT_BOX_WIDTH - 40);
Button sendButton = new Button("send");
sendButton.setId("sendButton");
sendButton.setPrefHeight(30);
sendButton.setOnMouseClicked(event -> {
VBox vBox = addMsg(
"Aran",
"hi, i'm aran",
"5:19");
vBox.setAlignment(Pos.TOP_LEFT);
chatHistory.getChildren().add(vBox);
VBox vBox2 = addMsg(
"Farnam",
"oh, I love you!",
"5:19");
vBox2.setAlignment(Pos.TOP_RIGHT);
chatHistory.getChildren().add(vBox2);
});
ScrollPane scrlPane = new ScrollPane(chatHistory);
scrlPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrlPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
scrlPane.setId("scrolPane");
chatBox = new VBox(new HBox(backToPublicChat, chatWindowInfo), scrlPane, new HBox(messageField, sendButton));
chatBox.setId("chatBox");
chatBox.getStylesheets().add("TowDef/GUI//chatBoxCSS.css");
}
Also I just need to set the HPos but i don't know how to, so I used the Pos.TOP_RIGHT. does anyone know how to achieve this? any advice on how to make the chatbox in a better way will be well appreciated:)