如何从TextFlow复制文本

时间:2017-05-03 10:25:22

标签: javafx

我有多个VBox内的TextFlow。如何使此文本可选择/可复制?

public class ExampleController implements Initializable {

    @FXML
    private VBox box;

    @Override
    public void initialize(final URL location, final ResourceBundle resources) {
    final TextFlow tf = new TextFlow();
    final Text t0 = new Text("First part");
    final Text t1 = new Text(", second");      
    final Text t2 = new Text(" and third");
    t0.getStyleClass().add("first-part-styling");
    t1.getStyleClass().add("second-part-styling");
    t2.getStyleClass().add("third-part-styling");
    tf.getChildren().addAll(t0, t1, t2);
    this.box.getChildren().add(tf);
    }
}

我使用TextFlowText,因为我需要在同一个句子中使用不同的样式。

2 个答案:

答案 0 :(得分:1)

你不能,使用Text,因为这个类应该只显示文本。但您可以使用TextField代替:

public class JavaFXTest extends Application {

    @Override
    public void start(Stage primaryStage) {

        StackPane root = new StackPane();
        final TextFlow tf = new TextFlow();
        final Text t0 = new Text("First part");
        final Text t1 = new Text(", second");
        final TextField t2 = new TextField(" and third");
        t2.setEditable(false);
        t2.setBackground(Background.EMPTY);
        t2.setFocusTraversable(false);

        tf.getChildren().addAll(t0, t1, t2);
        root.getChildren().add(tf);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

third text is not selected third text is selected

编辑您可以查看一下 Rich-text area for JavaFX。 GitHub上的这个开源项目提供了一个可定制的文本区域。虽然没有试过......

答案 1 :(得分:0)

试试这个

   ObservableList<Node> nodesTextFlow = box.getChildren();
        StringBuilder sb = new StringBuilder();
        for (Node node : nodesTextFlow) {

            ObservableList<Node> nodesText = ((TextFlow) node).getChildren();
            for (Node node1 : nodesText) {
                sb.append((((Text) node1).getText()));
            }
    }
   String txt = sb.toString();