class DraggablePanelsView : View("Draggable Panels") {
override val root = borderpane {
center = pane {
add(
makeDraggable(LoginFrag().root as Node).apply {
relocate(0.0, 0.0)
}
)
add(
makeDraggable(ConfirmationFrag().root as Node).apply {
relocate(0.0, 67.0)
}
)
add(
makeDraggable(ProgressFrag().root as Node).apply {
relocate(0.0, 106.0)
}
)
}
bottom = checkbox("Drag mode", dragModeActiveProperty)
setPrefSize(500.0, 500.0)
paddingAll = 10.0
style {
fontSize = 16.px
}
}
}
val dragModeActiveProperty = booleanProperty(false)
fun makeDraggable(node: Node): Node {
val dragContext = DragContext()
val wrapGroup = Group(node)
wrapGroup.addEventFilter(
MouseEvent.ANY
) { mouseEvent ->
if (dragModeActiveProperty.value) { // 为所有的子节点禁用鼠标事件
mouseEvent.consume()
}
}
wrapGroup.addEventFilter(
MouseEvent.MOUSE_PRESSED
) { mouseEvent ->
if (dragModeActiveProperty.value) { // 记住鼠标光标的初始坐标和node位置
dragContext.mouseAnchorX = mouseEvent.x
dragContext.mouseAnchorY = mouseEvent.y
dragContext.initialTranslateX = node.translateX
dragContext.initialTranslateY = node.translateY
}
}
wrapGroup.addEventFilter(
MouseEvent.MOUSE_DRAGGED
) { mouseEvent ->
if (dragModeActiveProperty.value) { // 通过增量计算鼠标光标动作来从初始位置移动node
node.translateX = (dragContext.initialTranslateX
+ mouseEvent.x
- dragContext.mouseAnchorX)
node.translateY = (dragContext.initialTranslateY
+ mouseEvent.y
- dragContext.mouseAnchorY)
}
}
return wrapGroup
}
private class DragContext {
var mouseAnchorX = 0.0
var mouseAnchorY = 0.0
var initialTranslateX = 0.0
var initialTranslateY = 0.0
}
val styleStr = """
-fx-background-color: white;
-fx-border-color: black;
-fx-border-width: 1;
-fx-border-radius: 6;
-fx-padding: 6;
""".trimIndent()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。