I want to change the alignment of the component based on the width of the label text, and set this by listening for the width change. But the width obtained outside the listener is always 0, and setting the parent component's alignment inside the listener does not work
It doesn't work
@Overridepublic void initData(Object object) { if (object instanceof ChatItemEntity chatItemEntity){ Platform.runLater(() -> { chatItemImageView.setImage(new Image(chatItemEntity.getAvatar())); chatItemLabel.setText(chatItemEntity.getContent()); double maxWidth = chatItemLabel.getMaxWidth(); chatItemLabel.widthProperty().addListener((observableValue, oldVal, newVal) -> { if (newVal.doubleValue() <= maxWidth){ chatItemHBox.setAlignment(Pos.CENTER_LEFT); } }); }); }}
This is working! why?
@Override public void initData(Object object) { if (object instanceof ChatItemEntity chatItemEntity){ Platform.runLater(() -> { chatItemImageView.setImage(new Image(chatItemEntity.getAvatar())); chatItemLabel.setText(chatItemEntity.getContent()); double maxWidth = chatItemLabel.getMaxWidth(); chatItemLabel.widthProperty().addListener((observableValue, oldVal, newVal) -> { if (newVal.doubleValue() <= maxWidth){ } }); chatItemHBox.setAlignment(Pos.CENTER_LEFT); }); } }
This is fxml
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.control.Label?><?import javafx.scene.image.ImageView?><?import javafx.scene.layout.HBox?><HBox fx:id="chatItemHBox" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.imtp.client.controller.ChatItemController"><children><ImageView fx:id="chatItemImageView" fitHeight="40.0" fitWidth="40.0" pickOnBounds="true" preserveRatio="true" /><Label fx:id="chatItemLabel" wrapText="true" maxWidth="100"/></children></HBox>