Đây là đoạn mã của tôi.JavaFX: textArea.setScrollTop (Double.MAX_VALUE) không phải lúc nào cũng hoạt động
textArea.setText(someNewText)
textArea.positionCaret(textArea.getText().length());
textArea.setEditable(true);
textArea.setScrollTop(Double.MAX_VALUE);
Tôi sử dụng textArea.setScrollTop(Double.MAX_VALUE)
để cuộn textarea xuống dưới cùng (giải pháp tôi tìm thấy trên internet). Nó hoạt động, nhưng không phải lúc nào. Tôi đã lưu ý rằng nó không thể làm việc chỉ khi thanh cuộn dọc không hiển thị trước khi gọi mã này và hiển thị sau khi mã được thực hiện. Khi thanh cuộn dọc hiển thị trước khi gọi mã này, sau đó cuộn xuống dưới luôn hoạt động. Làm thế nào để sửa chữa nó? Có lẽ tôi nên làm cho thanh cuộn dọc luôn luôn có thể nhìn thấy? Nếu có, thì làm sao - tôi không tìm ra giải pháp.
EDIT: Đây là mã mẫu:
public class JavaFxApp1 extends Application{
private TextArea textArea;
@Override
public void start(Stage stage) throws Exception {
Button button=new Button("Press here");
textArea=new TextArea();
VBox vbox = new VBox(button,textArea);
button.setOnAction((event)->{
textArea.appendText("###This is a very long string:some text some text some text some text some"
+ " text some text some text some text some text some text"
+ " text some text some text some text some text some text"
+ " text some text some text some text some text some text .\n");
textArea.selectEnd();
textArea.deselect();
textArea.setScrollTop(Double.MAX_VALUE);
});
textArea.setEditable(true);
textArea.setWrapText(true);
textArea.setStyle("-fx-font-size:14px;-fx-focus-color: transparent;-fx-font-family: monospace;");
Scene scene=new Scene(vbox);
stage.setTitle("SomeTitle");
stage.setScene(scene);
stage.setMinHeight(400);
stage.setMinWidth(800);
stage.show();
}
}
Đây là kết quả khi tôi nhấn nút 4 lần: Như bạn thấy nó không di chuyển đến phía dưới. Sau khi tôi nhấn nút lần nữa (lần thứ năm) tôi có kết quả như sau: Bây giờ, như bạn thấy nó đã được cuộn xuống dưới cùng. Tôi đã cố gắng thêm:
ScrollPane scrollPane = (ScrollPane) textArea.lookup(".scroll-pane");
scrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS);
để làm cho thanh cuộn luôn hiển thị - hiển thị nhưng sau 4 lần không cuộn xuống dưới cùng.
Cách khắc phục?
Đây là lỗi, vì vậy tôi đã mở báo cáo lỗi. Xem https://bugs.openjdk.java.net/browse/JDK-8189732 –