Reputation: 1
I'm working on a Kotlin application with a JavaFx UI. I have hidden the stage and when I want to show it from another thread it doesn't show!
The main function tries to write some data to a socket. If there's any error it will launch the Form.kt application. When the Form starts it will start ShowThread.kt; inside this class I have created a ServerSocket and still running, when I run main again it will connect to the ServerSocket and write some data to the server, and the server will show the Form after reading the data, but it doesn't show!
This is the main.kt:
fun main(args: Array<String>) {
try {
val socket = Socket(InetAddress.getLocalHost(), 4848)
val bos = BufferedOutputStream(socket.getOutputStream())
val request = "OPEN_UI.command"
val buffer = ByteArray(1024)
bos.write(request.toByteArray())
bos.flush()
bos.close()
socket.close()
}catch (e : ConnectException){
thread {
Application.launch(Form::class.java)
}
}
}
This is the Form.kt:
class Form: Application() {
lateinit var mStage: Stage
override fun start(stage: Stage) {
this.mStage = stage
val loader = FXMLLoader(javaClass.getResource("views/main.fxml"))
val scene = Scene(loader.load(),800.0,600.0)
stage.scene = scene
scene.stylesheets.add(javaClass.getResource("style/main.css").toExternalForm())
stage.show()
stage.setOnCloseRequest {
it.consume()
stage.hide()
}
val service = ShowThread(this)
service.start()
}
fun show(): Unit {
Platform.runLater {
mStage.show()
}
}
}
This is the ShowThread.kt:
class ShowThread(val form: Form): Thread() {
override fun run() {
try {
val port = 4848
val address = InetAddress.getLocalHost()
val socket = ServerSocket(port,50, address)
while (true) {
val client = socket.accept()
val ibs = BufferedInputStream(client.getInputStream())
val buffer = ByteArray(1024)
val request = StringBuilder()
while (ibs.read(buffer) != -1){
request.append(String(buffer))
}
println("Showing Main Form")
form.show()
}
}catch (e : Exception){
println(e.message)
}
}
}
Upvotes: 0
Views: 263
Reputation: 1
Thanks Brian Tompsett and David Conrad. I solved my problem by creating another variable and make infinite loop that check the variable if changed or not , and i can change the this variable from my server.
so my code will be :
fun show() {
show = true
}
for show function and the close request listener :
stage.setOnCloseRequest {
it.consume()
stage.hide()
println("hide stage")
Platform.runLater {
while (!show){
Thread.sleep(100)
}
stage.show()
println("Show stage")
show = false
}
}
Upvotes: 0