2016-08-23 139 views
0

在我的应用程序中,我每隔2分钟将文本附加到TextArea。当我添加新行到TextArea时,自动滚动自动关闭。但我想保持滚动,我保持滚动按钮。如何在JavaFX中做到这一点。如何控制JavaFX TextArea自动滚动?

logTextArea.appendText("Here i am appending text to text area"+"\n"); 
logTextArea.setScrollTop(Double.MIN_VALUE); 

我试过这个但滚动自动下去,但我需要保持我的滚动选择位置,我不想自动下去。

我该怎么做?

回答

0

也许你可以添加一个changeListener给TextArea,它什么都不做,或者每当它里面的文本被改变时,它就滚动到TextArea的顶部。

logTextArea.textProperty().addListener(new ChangeListener<Object>() { 
    @Override 
    public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) { 
     logTextArea.setScrollTop(Double.MIN_VALUE); //this will scroll to the top 
    } 
}); 

现在,当您向TextArea发送logTextArea.appendText("Here i am appending text to text area"+"\n");时,它应该停留在顶部。

的想法摘自:JavaFX TextArea and autoscroll

+0

我需要添加这个吗?是指类控制器类或应用程序扩展类@ user2882590 – epn

+0

您有一个控制器类,您声明了TextArea。如果我没有记错,在'public void initialize()'函数中,如果来自fxml文件,可以将此侦听器添加到'logTextArea'中。如果没有,那么你可以在创建它之后添加这个监听器。所以之后:'TextArea logTextArea = new TextArea();' – sundri23

+0

好吧,但我的问题是添加一些文本到文本区域后,我滚动我的按钮到中间,之后,当我添加文本滚动按钮不会走上去需要留在中间只有我想那样。我能怎么做 ? – epn

1

最直接的方法就是记住插入符的位置,并恢复它它就会通过appendTextsetText移动后。

这里是你如何能做到这一点:

int caretPosition = area.caretPositionProperty().get(); 
area.appendText("Here i am appending text to text area"+"\n"); 
area.positionCaret(caretPosition); 
+0

当在循环中用于appendText时,这起作用。 –

0

您可以编写自己的功能,将文本追加。在此方法中,您可以使用setText而不是appendText,因为appendText会自动滚动到内容的末尾(setText滚动到开头,但可以通过将scrollTopProperty恢复为其先前值来抑制此问题)。

public class Main extends Application { 
    @Override 
    public void start(Stage primaryStage) { 
     try { 
      BorderPane root = new BorderPane(); 
      Scene scene = new Scene(root,400,400); 

      TextArea ta = new TextArea(); 
      root.setCenter(ta); 
      Button button = new Button("Append"); 
      button.setOnAction(e -> { 
       appendTextToTextArea(ta, "BlaBlaBla\n"); 
      }); 
      root.setBottom(button); 

      primaryStage.setScene(scene); 
      primaryStage.show(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

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


    /** 
    * Appends text to the end of the specified TextArea without moving the scrollbar. 
    * @param ta TextArea to be used for operation. 
    * @param text Text to append. 
    */ 
    public static void appendTextToTextArea(TextArea ta, String text) { 
     double scrollTop = ta.getScrollTop(); 
     ta.setText(ta.getText() + text); 
     ta.setScrollTop(scrollTop); 
    } 
} 

注:

另外,您还可以扩展TextArea和过载appendText能够指定是否要移动的滚动条:

public class AppendableTextArea extends TextArea { 

    public void appendText(String text, Boolean moveScrollBar) { 
     if (moveScrollBar) 
      this.appendText(text); 
     else { 
      double scrollTop = getScrollTop(); 
      setText(getText() + text); 
      setScrollTop(scrollTop); 
     } 
    } 
} 

和用法:

AppendableTextArea ta = new AppendableTextArea(); 
ta.appendText("BlaBlaBla\n", false);