javafx 怎么实现拖动TreeItem
时间: 2024-05-03 12:17:00 浏览: 157
要在 JavaFX 中实现拖放 `TreeItem`,可以使用 `TreeView` 的 `setCellFactory` 方法来自定义每个 `TreeItem` 的外观和行为。以下是一个简单的实现:
```java
final TreeView<String> treeView = new TreeView<>();
treeView.setRoot(root); // root 是根节点
treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
@Override
public TreeCell<String> call(TreeView<String> tv) {
TreeCell<String> cell = new TreeCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(item);
}
};
cell.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Dragboard db = cell.startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.putString(cell.getItem());
db.setContent(content);
event.consume();
}
});
cell.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
event.acceptTransferModes(TransferMode.MOVE);
}
event.consume();
}
});
cell.setOnDragEntered(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
cell.setOpacity(0.3);
}
}
});
cell.setOnDragExited(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
cell.setOpacity(1);
}
});
cell.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
TreeItem<String> draggedItem = new TreeItem<>(db.getString());
TreeItem<String> parent = treeView.getSelectionModel().getSelectedItem();
parent.getChildren().add(draggedItem);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
});
return cell;
}
});
```
这个实现中,`setOnDragDetected` 方法设置了当用户开始拖动一个节点时要执行的操作,`setOnDragOver` 方法设置了当用户将一个节点拖到另一个节点上时要执行的操作,`setOnDragDropped` 方法设置了当用户松开鼠标时要执行的操作。此外,还设置了 `setOnDragEntered` 和 `setOnDragExited` 方法以改变节点的外观。
阅读全文