gpt4 book ai didi

event-handling - 如何在 JavaFX 中移动 VBox 中的项目(通过拖动更改顺序)?

转载 作者:行者123 更新时间:2023-12-04 02:10:10 25 4
gpt4 key购买 nike

我想在 VBox 中拖动 TitledPane。我在 VBox 中有 n 个 Titlepane。我想在拖动时更改它们的顺序。我尝试了一些 MouseEvents 和 DragEvents。但它不适合我。

但我需要将 Titledpane 移动到哪个位置的索引。基于此,我需要在后端做一些事情。请帮我。

谢谢

最佳答案

这对我有用...

private static final String TAB_DRAG_KEY = "titledpane";
private ObjectProperty<TitledPane> draggingTab;
@Override
public void start(Stage primaryStage) throws Exception {
draggingTab = new SimpleObjectProperty<TitledPane>();
VBox vbox=new VBox();
for(int i=0;i<4;i++) {
final TitledPane pane=new TitledPane();
pane.setText("pane"+(i+1));
vbox.getChildren().add(pane);
pane.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
final Dragboard dragboard = event.getDragboard();
if (dragboard.hasString()
&& TAB_DRAG_KEY.equals(dragboard.getString())
&& draggingTab.get() != null) {
event.acceptTransferModes(TransferMode.MOVE);
event.consume();
}
}
});
pane.setOnDragDropped(new EventHandler<DragEvent>() {
public void handle(final DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
Pane parent = (Pane) pane.getParent();
Object source = event.getGestureSource();
int sourceIndex = parent.getChildren().indexOf(source);
int targetIndex = parent.getChildren().indexOf(pane);
List<Node> nodes = new ArrayList<Node>(parent.getChildren());
if (sourceIndex < targetIndex) {
Collections.rotate(
nodes.subList(sourceIndex, targetIndex + 1), -1);
} else {
Collections.rotate(
nodes.subList(targetIndex, sourceIndex + 1), 1);
}
parent.getChildren().clear();
parent.getChildren().addAll(nodes);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
});
pane.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Dragboard dragboard = pane.startDragAndDrop(TransferMode.MOVE);
ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(TAB_DRAG_KEY);
dragboard.setContent(clipboardContent);
draggingTab.set(pane);
event.consume();
}
});
}
TitledPane pane=new TitledPane("MAIN",vbox);
primaryStage.setScene(new Scene(pane, 890, 570));
primaryStage.show();
}

关于event-handling - 如何在 JavaFX 中移动 VBox 中的项目(通过拖动更改顺序)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18929161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com