JavaFX 3D中如何获取被点击的Box并关联角色数据
解决JavaFX 3D Box点击关联角色数据的问题
核心思路
每个Box对应一个角色节点(代码中的chars对象),通过JavaFX节点的用户数据绑定功能,将角色数据直接关联到对应的Box上,点击时即可取出对应数据进行展示。
具体实现步骤
1. 绑定角色数据到Box
在创建Box的循环中,使用setUserData()方法将当前遍历的角色节点绑定到Box上:
for (Node chars: chapt.getChildren()) { double height = rnd.nextDouble() * 500; Box box = new Box(chars.getHeight(), height, chars.getWidth()); // 将角色节点绑定到Box的用户数据中 box.setUserData(chars); // 材质与颜色设置 PhongMaterial mat = new PhongMaterial(); mat.setDiffuseColor(randomColor()); box.setMaterial(mat); // 位置设置 box.setLayoutY(-height * 0.5); box.setTranslateX(xStart-(chars.getHeight()/2)); box.setTranslateZ(yStart-(chars.getWidth()/2)); grid.getChildren().addAll(box); Boxliste.add(box); }
2. 给Box添加点击事件监听器
同样在创建Box的循环内,为每个Box添加鼠标点击事件,取出绑定的角色数据并展示:
box.setOnMouseClicked(event -> { // 取出绑定的角色节点 Node characterNode = (Node) box.getUserData(); if (characterNode != null && characterNode.getType() == NodeType.CHARACTER) { // 获取角色相关数据 String characterName = characterNode.getName(); double metric = characterNode.getMetric(); // 弹出窗口展示数据(示例使用Alert,可自定义窗口样式) Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("角色信息"); alert.setHeaderText(characterName); alert.setContentText(String.format("关联占比: %.2f", metric)); alert.showAndWait(); } });
3. 额外注意事项
- 确保自定义的
Node类和NodeType枚举可正常访问,避免类型转换异常; - 如果3D场景中Box无法被点击,可尝试:
- 设置
box.setPickOnBounds(true);,让Box的整个边界区域都能接收点击事件; - 检查Box尺寸是否过小,避免拾取区域无法被触发;
- 确认场景相机设置正确,没有遮挡Box的拾取路径。
- 设置
内容的提问来源于stack exchange,提问作者Bashan
相关产品推荐
相关产品推荐

