Reputation: 736
I'm trying to create a text area that whenever a text is added, it will scroll to the bottom. With the help of ChatGPT and all the documentation I could find, I ended up with this, but it doesn't work.
import javafx.application.Application
import javafx.application.Platform
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.ScrollPane
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.stage.Stage
import org.fxmisc.richtext.InlineCssTextArea
class MainApp : Application() {
override fun start(primaryStage: Stage) {
// Create a StyledTextArea to act as the console
val console = InlineCssTextArea().apply {
isWrapText = true
isEditable = false
}
// Wrap the console in a ScrollPane to make it scrollable
val scrollPane = ScrollPane(console).apply {
isFitToWidth = true
isFitToHeight = true
hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER
vbarPolicy = ScrollPane.ScrollBarPolicy.ALWAYS
}
var line = 1
// Create a button to simulate adding text to the console
val button = Button("Add Colored Text").apply {
setOnAction {
Platform.runLater {
console.appendText("New line added to console at ${line++}" + "\n")
scrollPane.vvalue = 1.0
}
}
}
val vbox = VBox(button, scrollPane).apply {
VBox.setVgrow(scrollPane, Priority.ALWAYS)
}
// Create the Scene
val scene = Scene(vbox, 600.0, 450.0)
// Set up the Stage
primaryStage.title = "JavaFX Console"
primaryStage.scene = scene
primaryStage.show()
}
}
// Entry point for the application
fun main(args: Array<String>) {
Application.launch(MainApp::class.java, *args)
}
Moreover, the scrollbar looks as if it is empty. I can only scroll with the mouse wheel.
What am I doing wrong?
Upvotes: 0
Views: 32