一、问题场景

  在上一篇中,我们将窗口的默认标题栏隐藏从而导致鼠标点击窗体无法进行拖动。

二、解决思路

  给组件添加鼠标按下事件监听器和鼠标拖动事件监听器。

三、代码实现

/**
* 程序入口
* @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);
}
}

效果演示图:

最新文章

  1. 关联查询 join on 和比较运算符 in
  2. IP一些基础知识
  3. Android(java)学习笔记119:继承中父类没有无参构造
  4. func_get_args的使用
  5. golang入门-- 一个2D的图形库学习
  6. LeeCode-Happy Number
  7. backbone HTTP方法中 options参数
  8. HBase BlockCache
  9. JS之This的用法
  10. git tag用法
  11. appstore跳转
  12. 转载-js如何设置网页横屏和竖屏切换
  13. 内联汇编_把a值赋给b的汇编代码
  14. php生成随机颜色代码
  15. 知乎大神对IAAS,SAAS,PAAS区别的理解
  16. Google的代码高亮-code-prettify
  17. 【JQ】鼠标经过一组button,弹出各自的气泡图片
  18. hdu刷题2
  19. 校招小白机考入坑之从键盘输入java的各种数据类型
  20. Hadoop格式化HDFS报错java.net.UnknownHostException: centos64

热门文章

  1. CentOS搭建LAMP环境
  2. jQuery/CSS3大屏下拉菜单 自定义子菜单内容
  3. HTML编码
  4. 探索ORACLE之ASM概念
  5. 【转】Maven实战(七)---传递依赖
  6. Java设计模式系列之中介者模式
  7. Define custom @Required-style annotation in Spring
  8. POJ 2762 Going from u to v or from v to u? (强连通分量缩点+拓扑排序)
  9. Java NIO类库Selector机制解析(上)
  10. C#学习笔记(九):LINQ和表达式树