如何在RichTextFx中设置垂直滚动

How to set the vertical scroll in RichTextFx

我希望能够将垂直滚动设置到 RichTextFX. By the looks of this 线程中 InlineStyleTextArea 的顶部或底部,moveTo(..) 应该可以解决问题。但这对我不起作用。我也试过 selectRange(..)positionCaret(..)。下面是我的测试程序,我是否误解了上面链接中提到的"workaround of repositioning the caret"?

import org.fxmisc.richtext.InlineStyleTextArea;

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.HBox;
    import javafx.stage.Stage;

    public class RichTextFXTest extends Application {

    @Override
    public  void start(Stage stage) {

        InlineStyleTextArea<StyleInfo> area = new InlineStyleTextArea<>(
                new StyleInfo(), styleInfo -> styleInfo.toCss());
                area.setPrefSize(300, 300);
        area.setWrapText(false);
                area.setEditable(false);

                StringBuilder largeText = new StringBuilder();

                for (int i = 0; i < 5000; i++) {
                largeText.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n");
                }

                area.replaceText(largeText.toString());

                // None of the two rows below works.
                //area.selectRange(1000, 1100);
                //area.moveTo(1100);
                //area.positionCaret(1100);

                HBox rootLayout = new HBox();
                rootLayout.setPrefSize(300, 300);
                rootLayout.getChildren().add(area);

                Scene scene = new Scene(rootLayout);
                stage.setScene(scene);
                stage.show();
     }

     // Style class
        class StyleInfo {
            String toCss() {
                return "-fx-fill: red;
            } 
    }

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

@Tomas Mikula 在 this github 线程中提供了答案。我想我也应该把答案放在这里。

The problem with your example is that the moveTo/selectRange work-around does not work before the skin is instantiated. If in your example you surround the selectRange in Platform.runLater, that will give you the desired result. Also note that the range is given in character indices, not line numbers.

Platform.runLater(() -> area.selectRange(10000, 10100));

In the code that results from user's interaction after the text area has already been shown, you will not need Platform.runLater anymore.

你可以这样做:

int pos = 1100;
area.moveTo(pos);
area.requestFollowCaret();