我有一個TextArea
不會向下滾動時,我添加文本在它。我想用this answer,但我TextArea
連接到StringProperty
這樣的:自動向下滾動TextArea
consoleTextArea.textProperty().bind(textRecu);
因此,答案不爲我工作,有另一種方式讓我TextArea
向下滾動每次我更新它通過綁定?
我有一個TextArea
不會向下滾動時,我添加文本在它。我想用this answer,但我TextArea
連接到StringProperty
這樣的:自動向下滾動TextArea
consoleTextArea.textProperty().bind(textRecu);
因此,答案不爲我工作,有另一種方式讓我TextArea
向下滾動每次我更新它通過綁定?
這裏是我在評論關於添加監聽器到textRecu的意思的快速演示。 Yep consoleTextArea.textProperty()由於綁定而無法更改。但textRecu沒有綁定=>可以改變,我們可以添加監聽器。
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private StringProperty textRecu = new SimpleStringProperty();
private TextArea consoleTextArea = new TextArea();
@Override
public void start(Stage primaryStage) throws Exception{
VBox root = new VBox();
Button button = new Button("Add some text");
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
//here you change textRecu and not consoleTextArea.textProperty()
textRecu.setValue(textRecu.getValue() +"New Line\n");
}
});
root.getChildren().addAll(consoleTextArea, button);
consoleTextArea.textProperty().bind(textRecu);
//here you also add listener to the textRecu
textRecu.addListener(new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<?> observable, Object oldValue,
Object newValue) {
// from stackoverflow.com/a/30264399/1032167
// for some reason setScrollTop will not scroll properly
//consoleTextArea.setScrollTop(Double.MAX_VALUE);
consoleTextArea.selectPositionCaret(consoleTextArea.getLength());
consoleTextArea.deselect();
}
});
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我有一個小錯誤,但是現在如果它被鏈接,它不會去到textarea的末尾,但到end-1行 –
我的錯誤來自事實綁定更新我的字符串在我的textarea之前 –
@EvansBelloeil我認爲這是TextArea setText()中的某種刷新錯誤,但我可以wrong.This帖子是一個相當的解決方案:http://stackoverflow.com/a/30264399/1032167只需添加'consoleTextArea.selectPositionCaret(consoleTextArea.getLength()); consoleTextArea.deselect();'而不是'consoleTextArea.setScrollTop(Double.MAX_VALUE);' – varren
你也許可以添加監聽器textRecu StringProperty。 – varren
不錯,我在我的帖子中說過,當有人因爲綁定而發生變化時,聽衆不會被調用,我想... –