如您所见,我的文本受到 label
的限制。如何使 label
调整大小以完全适合文本,并相应地调整 VBox
和 GridPane
的大小。我只想垂直调整大小。
我的 FXML:
<VBox fx:id="body"
alignment="TOP_CENTER"
prefHeight="150"
GridPane.vgrow="SOMETIMES"
prefWidth="300"
GridPane.columnIndex="0"
GridPane.rowIndex="1" spacing="5">
<Label alignment="CENTER" textAlignment="JUSTIFY" fx:id="word" maxWidth="268"/>
<Pane prefHeight="10" VBox.vgrow="NEVER"/>
<Label alignment="CENTER" textAlignment="JUSTIFY" wrapText="true" fx:id="meaning" maxWidth="268" />
<Label alignment="CENTER" textAlignment="JUSTIFY" wrapText="true" fx:id="sentence" maxWidth="268" />
</VBox>
这个 VBox
在 GridPane
里面:
<GridPane fx:id="base"
alignment="CENTER"
prefHeight="210.0"
maxWidth="310.0"
stylesheets="@style.css"
vgap="0" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sample.Controller">
...
最小的、完整的和可验证的示例按照@James_D 的要求
主类:
public class Main extends Application {
private Stage stage;
private StackPane stackPane;
@Override
public void start(Stage primaryStage) throws Exception{
stage = primaryStage;
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = (Parent) loader.load();
stackPane = new StackPane(root);
Scene scene = new Scene(stackPane);
scene.setFill(Color.WHITE);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller 类:
public class Controller implements Initializable{
@FXML private Label label1;
@FXML private Button changeLabel;
private StringProperty labelString = new SimpleStringProperty();
@Override
public void initialize(URL location, ResourceBundle resources) {
labelString.setValue("aasdasd sad asdasd asdasda");
label1.textProperty().bind(labelString);
}
@FXML
public void clicked(MouseEvent e){
labelString.setValue("asdsadasd asdasdasd sfdgsfwoef fgtrhfgbdrgdf dfgdfivbjkfd gdfgidfjvdf gdfgjldkvbdf gjdilgjdfv dfgojdflkgdf ");
}
}
示例.fxml:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" maxHeight="Infinity">
<children>
<VBox fx:id="body"
alignment="CENTER"
maxHeight="Infinity"
GridPane.vgrow="SOMETIMES"
prefWidth="300"
GridPane.columnIndex="0"
GridPane.rowIndex="1" spacing="5">
<Label alignment="CENTER" VBox.vgrow="ALWAYS" wrapText="true" textAlignment="CENTER" fx:id="label1" maxWidth="268"/>
<Button fx:id="changeLabel" text="Change" minWidth="50" onMouseClicked="#clicked" maxWidth="Infinity" />
</VBox>
</children>
期望: 当我按下“更改”按钮时,所有内容都应调整大小以提供足够的空间来显示文本。
问题: 当我按下“更改”按钮时,UI 保持不变,未显示全文。
最佳答案
假设您希望文本换行,标签将需要能够垂直增长。添加属性
maxHeight="Infinity"
到每个标签。您还使用 prefHeight="150"
限制了 VBox
的整体高度;删除该属性并让 VBox
计算出自己的高度。同样,您可能希望从 GridPane
中删除 prefHeight
属性。
关于java - 如何根据 JavaFx 中标签中的文本调整 VBox 和 Label 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35114338/