코드에서 몇 가지 문제가 있습니다
- 당신은 상관없이 타이머 무슨 일이 일어나고 있는지에, 한 번만 경고 표시가.
- 타이머의 경고 결과에 반응하는 코드는 항상 동일한 초기 결과를 조사합니다.
- 불행히도
val result = alert1.showAndWait
을 타이머의 애니메이션 업데이트 이벤트 내부로 이동하더라도 JavaFX은 그러한 루틴 내에서 showAndWait
을 호출하는 것을 불법으로 만듭니다.
용액이 닫히는 alert1
반응 onHidden
대한 이벤트 핸들러를 생성하는 것이다. 대화 상자를 닫는 데 사용되는 단추 유형은 alert1.result
에 저장되므로이를 사용하여 수행 할 작업을 결정할 수 있습니다.
레이블 값을 변경하는 데 도움이되도록 StringProperty
을 추가했습니다. 다음 예제는 당신이 달성하기를 원하는 좋은 시작점이되어야합니다 ...
import scalafx.Includes._
import scalafx.animation.PauseTransition
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.beans.property.StringProperty
import scalafx.scene.Scene
import scalafx.scene.layout.VBox
import scalafx.scene.control.{Alert, ButtonType, Label}
import scalafx.scene.control.Alert.AlertType
import scalafx.util.Duration
object main extends JFXApp {
// String property for the text in myLabel.
val strProp = StringProperty("Some Text")
// Declare this so that it's accessible from timerA.onFinished.
val myLabel = new Label {
// Bind the text property to the value of strProp.
// When strProp's value changes, so does the label's text.
text <== strProp
}
stage = new PrimaryStage() {
scene = new Scene {
root = new VBox {
children = myLabel
}
}
}
// Custom buttons.
val ButtonTypeOne = new ButtonType("Change the text")
val ButtonTypeTwo = new ButtonType("No")
// Create the timer. This goes off after 5,000ms (5 seconds) - after play is called.
val timerA = new PauseTransition(Duration(5000))
// Alert dialog.
// Note: JavaFX forbids use of showAndWait within animation processing, so we must use
// an onHidden event instead.
val alert1 = new Alert(AlertType.Warning) {
initOwner(stage)
title = "Warning!!!"
headerText = "Header"
contentText = "Do you need to change the text?"
buttonTypes = Seq(ButtonTypeOne, ButtonTypeTwo, ButtonType.Cancel)
}
// React to the dialog being closed.
alert1.onHidden = {_ =>
alert1.result.value match {
// If button type one, change the property value.
// Note alert1.result.value is a JavaFX ButtonType, so use .delegate for the match.
case ButtonTypeOne.delegate => strProp.value = "Changed!"
// Otherwise, do nothing.
case _ =>
}
// Start the timer once more.
// This is going to be a very annoying app! ;-)
timerA.playFromStart()
}
// When the timer goes off, show the alert.
timerA.onFinished = {_ =>
alert1.show()
}
// Start the timer for the first time.
timerA.play
}