JavaFX(三)窗口拖动
2024-08-19 22:28:22
一、问题场景
在上一篇中,我们将窗口的默认标题栏隐藏从而导致鼠标点击窗体无法进行拖动。
二、解决思路
给组件添加鼠标按下事件监听器和鼠标拖动事件监听器。
三、代码实现
/**
* 程序入口
* @author Light
*/
public class JavaFXTest extends Application { @Override
public void start(Stage stage) { stage.initStyle(StageStyle.TRANSPARENT); VBox root = new VBox();
root.setId("root");
// 引入样式
root.getStylesheets().add(JavaFXTest.class.getResource("/resources/style.css").toString()); //顶部
VBox top = new VBox();
top.setId("top");
top.setPrefSize(300,26);
// 标题栏
AnchorPane title = new AnchorPane();
Label close = new Label();
close.setPrefWidth(33);
close.setPrefHeight(26);
close.setId("winClose");//winClose css样式Id
title.getChildren().add(close);
AnchorPane.setRightAnchor(close, 0.0);
AnchorPane.setTopAnchor(close, 5.0);
top.getChildren().add(title); // 内容
VBox content = new VBox();
content.setPrefWidth(300);
content.setMinHeight(200);
// 组装
root.getChildren().addAll(top, content);
Scene scene = new Scene(root);
stage.setScene(scene);
// 拖动监听器
DragUtil.addDragListener(stage, top);
// 显示
stage.show();
} /**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
} }
/**
* 工具类
* @author Light
*/
public class DragUtil {
public static void addDragListener(Stage stage,Node root) {
new DragListener(stage).enableDrag(root);
}
}
/**
* 拖拽监听器
* @author Light
*/
public class DragListener implements EventHandler<MouseEvent> { private double xOffset = 0;
private double yOffset = 0;
private final Stage stage; public DragListener(Stage stage) {
this.stage = stage;
} @Override
public void handle(MouseEvent event) {
event.consume();
if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
xOffset = event.getSceneX();
yOffset = event.getSceneY();
} else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
stage.setX(event.getScreenX() - xOffset);
if(event.getScreenY() - yOffset < 0) {
stage.setY(0);
}else {
stage.setY(event.getScreenY() - yOffset);
}
}
} public void enableDrag(Node node) {
node.setOnMousePressed(this);
node.setOnMouseDragged(this);
}
}
效果演示图:
最新文章
- 关联查询 join on 和比较运算符 in
- IP一些基础知识
- Android(java)学习笔记119:继承中父类没有无参构造
- func_get_args的使用
- golang入门-- 一个2D的图形库学习
- LeeCode-Happy Number
- backbone HTTP方法中 options参数
- HBase BlockCache
- JS之This的用法
- git tag用法
- appstore跳转
- 转载-js如何设置网页横屏和竖屏切换
- 内联汇编_把a值赋给b的汇编代码
- php生成随机颜色代码
- 知乎大神对IAAS,SAAS,PAAS区别的理解
- Google的代码高亮-code-prettify
- 【JQ】鼠标经过一组button,弹出各自的气泡图片
- hdu刷题2
- 校招小白机考入坑之从键盘输入java的各种数据类型
- Hadoop格式化HDFS报错java.net.UnknownHostException: centos64