我实际上正在开发一个没有窗口装饰的 ScalaFX 应用程序。 我想要做的是让它可以拖动,这样用户就可以随意移动它。
我通过简单地将拖动鼠标的坐标写入舞台 X/Y 坐标来设法移动舞台。然而,这导致了滞后和闪烁的窗口。
如何在ScalaFX中顺利实现拖动舞台?
最佳答案
这是一个对我来说效果很好的例子。它改编自“JavaFX 8 Introduction by Example”一书中的一个示例。与您的尝试相比如何?
import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.geometry.Point2D
import scalafx.scene.Scene
import scalafx.scene.input.MouseEvent
import scalafx.scene.paint.Color
import scalafx.stage.{WindowEvent, StageStyle}
object DraggableApp extends JFXApp {
private var anchorPt: Point2D = null
private var previousLocation: Point2D = null
stage = new PrimaryStage {
initStyle(StageStyle.TRANSPARENT)
scene = new Scene {
fill = Color.rgb(0, 0, 0, 1.0)
}
}
// Initialize stage to be movable via mouse
initMovablePlayer()
/**
* Initialize the stage to allow the mouse cursor to move the application
* using dragging.
*/
private def initMovablePlayer(): Unit = {
val scene = stage.getScene
scene.onMousePressed = (event: MouseEvent) => anchorPt = new Point2D(event.screenX, event.screenY)
scene.onMouseDragged = (event: MouseEvent) =>
if (anchorPt != null && previousLocation != null) {
stage.x = previousLocation.x + event.screenX - anchorPt.x
stage.y = previousLocation.y + event.screenY - anchorPt.y
}
scene.onMouseReleased = (event: MouseEvent) => previousLocation = new Point2D(stage.getX, stage.getY)
stage.onShown = (event: WindowEvent) => previousLocation = new Point2D(stage.getX, stage.getY)
}
}
编辑:关于您关于调整舞台大小的问题,我尝试了以下变体,它在右键单击和拖动时调整舞台大小;我没有看到任何闪烁(在 OS X 上)。
import javafx.scene.{input => jfxsi}
// (...)
object DraggableApp extends JFXApp {
private var previousHeight = 0.0
private var previousWidth = 0.0
// (...)
private def initMovablePlayer(): Unit = {
val scene = stage.getScene
scene.onMousePressed = (event: MouseEvent) => anchorPt = new Point2D(event.screenX, event.screenY)
scene.onMouseDragged = (event: MouseEvent) =>
if (anchorPt != null && previousLocation != null) {
if (event.getButton == jfxsi.MouseButton.PRIMARY) {
stage.x = previousLocation.x + event.screenX - anchorPt.x
stage.y = previousLocation.y + event.screenY - anchorPt.y
} else if (event.getButton == jfxsi.MouseButton.SECONDARY) {
stage.width = previousWidth + event.screenX - anchorPt.x
stage.height = previousHeight + event.screenY - anchorPt.y
}
}
scene.onMouseReleased = (_: MouseEvent) => reset()
stage.onShown = (_: WindowEvent) => reset()
def reset (): Unit = {
previousLocation = new Point2D(stage.getX, stage.getY)
previousHeight = stage.getHeight
previousWidth = stage.getWidth
}
}
}
关于scalafx - 使 ScalaFX 场景可拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691604/