JavaFX为什么VBox在添加更多儿童时会改变它的单元格大小

时间:2014-12-08 21:13:30

标签: javafx

我正在制作聊天应用程序。聊天内容显示在VBox中,每条消息都在Label中。当我向VBox添加更多标签时会出现问题 - 我看到所有消息标签都调整为较小的尺寸,而不考虑其内容。有人能告诉我怎样才能解决这个问题?谢谢 代码例如: FXML:

<AnchorPane id="AnchorPane" prefHeight="50.0" prefWidth="245.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="chatwithnolist.FXMLController">
   <children>
  <ScrollPane fx:id="scrollPane" layoutX="147.0" layoutY="23.0" prefHeight="351.0" prefWidth="600.0" AnchorPane.bottomAnchor="49.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
     <content>
        <VBox fx:id="vbox" prefHeight="348.0" prefWidth="596.0" spacing="5.0" />
     </content>
  </ScrollPane>
  <Button fx:id="button" layoutX="27.0" layoutY="363.0" mnemonicParsing="false" onAction="#buttonPressed" text="add to vbox" />
   </children>
</AnchorPane>

控制器:

@FXML
private ScrollPane scrollPane;
@FXML
private VBox vbox;
@FXML
private Button button;

@Override
public void initialize(URL url, ResourceBundle rb) {
    scrollPane.setFitToHeight(true);
    scrollPane.setFitToWidth(true);
}    

@FXML
private void buttonPressed(ActionEvent event) {
    Label label = new Label("bla bla\nbla bla\nbla bla\n");
    label.setStyle("-fx-background-color: #a1f2cd; "
            + "-fx-padding: 10;\n"
            + "-fx-spacing: 5;");
    vbox.getChildren().add(label);
}

2 个答案:

答案 0 :(得分:0)

VBox可以根据其父容器及其临时约束自动增长。但我想你的问题如下:你的VBox的内容比可用的应用程序大小要大。

这通常是使用ScrollPane

的情况

但在你的情况下,我建议使用ListView。它可以处理大量内容而没有任何性能缺陷,提供开箱即用的滚动功能。


编辑:

以下代码演示了ListView的一个工作示例:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<String> strings = FXCollections.observableArrayList();
        ListView<String> listView = new ListView<>(strings);

        Button addMessage = new Button("Press me");
        addMessage.setOnAction(ev -> strings.add("bla bla\nbla bla\nbla bla\n"));
        ToolBar toolbar = new ToolBar(addMessage);

        BorderPane root = new BorderPane(listView);
        root.setTop(toolbar);
        Scene scene = new Scene( root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

编辑#2:

相同的示例代码,但使用VBox + ScrollPane而不是ListView:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox vbox = new VBox();

        Button addMessage = new Button("Press me");
        addMessage.setOnAction(ev -> vbox.getChildren().add(new Label("bla bla\nbla bla\nbla bla\n")));
        ToolBar toolbar = new ToolBar(addMessage);

        BorderPane root = new BorderPane(new ScrollPane(vbox));
        root.setTop(toolbar);
        Scene scene = new Scene( root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

答案 1 :(得分:0)

我在Text内使用了BorderPane而不是Label,它解决了问题!