java fx add元素一个ScroolPane

时间:2016-05-03 14:05:08

标签: javafx

我已经搜索过,但没有找到答案。 我有一个滚动,一个按钮和一个textarea。当我按下按钮时,我取出了textarea中的值,然后我希望将文本放在scrool的右上角,如果再按下一次,等等。示例

                                  hello guys
                                  this is my label

文字区域按钮

这是我的fxml文件

  <AnchorPane id="AnchorPane" prefHeight="392.0" prefWidth="357.0"      xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"   fx:controller="indixischat.ChatController">
  <children>


  <Pane id="title" layoutX="14.0" layoutY="14.0" prefHeight="60.0" prefWidth="333.0" />
  <TextField  fx:id="text" layoutX="14.0" layoutY="362.0" prefHeight="17.0" prefWidth="299.0" />

  <Button fx:id="sendMessage" onAction="#sendMessage" layoutX="318.0" layoutY="365.0" mnemonicParsing="false" prefHeight="11.0" prefWidth="29.0" text="Button" />
  <ScrollPane fx:id="scroll" layoutX="14.0" layoutY="44.0" prefHeight="319.0" prefWidth="339.0">
    <content>
      <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="412.0" prefWidth="326.0" />
    </content>
  </ScrollPane>

1 个答案:

答案 0 :(得分:0)

您可以使用VBox作为ScrollPane中文本的容器。然后在每次Button点击时创建一个新的TextField并将其添加到VBox

public class Test extends Application {

  @Override
    public void start(Stage primaryStage) {

        TextField txtInput = new TextField();

        VBox boxTextFields = new VBox();
        boxTextFields.setAlignment(Pos.TOP_RIGHT);
        boxTextFields.setFillWidth(false);

        ScrollPane scrollPane = new ScrollPane(boxTextFields);
        scrollPane.setFitToWidth(true);

        Button button = new Button();
        button.setOnAction(e -> boxTextFields.getChildren().add(new TextField(txtInput.getText())));

        VBox root = new VBox(textField, button, scrollPane);
        root.setAlignment(Pos.TOP_CENTER);

        primaryStage.setScene(new Scene(root, 300, 300));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}