gpt4 book ai didi

java - 复选框状态下的 TreeView 传输

转载 作者:行者123 更新时间:2023-12-01 12:19:55 32 4
gpt4 key购买 nike

我有 2 个 TreeView,第一个填充有项目。

try {
CheckBoxTreeItem<String> treeRoot = new CheckBoxTreeItem<String>("Root");
treeRoot.setExpanded(true);

for (int i = 1; i <= 20; i++) {
item = new CheckBoxTreeItem<String>("item " + i);
treeRoot.getChildren().add(item);
}

treeView.setRoot(treeRoot);
treeView.setCellFactory(CheckBoxTreeCell.<String> forTreeView());
treePane.add(treeView, 0, 1);

} catch (Exception e) {
e.printStackTrace();
}

我想将选中复选框的项目传输到我的第二棵树。如果选中根项,则所有子项都必须添加到第二棵树中。子根也是如此。

我尝试过类似的方法,但它不起作用。

int length = treeView.getExpandedItemCount();

CheckBoxTreeItem<String> treeRoot = new CheckBoxTreeItem<String>("On the other side");
treeRoot.setExpanded(true);

try {
for (int i = 1; i <= length; i++) {
item = (CheckBoxTreeItem<String>) (treeView.getTreeItem(i));
if (item.isSelected()) {
treeRoot.getChildren().add(item);
}

}
treeView.setRoot(treeRoot);
treePaneExecution.add(treeView, 0, 1);
} catch (Exception e) {
e.printStackTrace();
}

如有任何建议,我们将不胜感激!

最佳答案

使用 CheckBoxTreeItemselectedProperty() 注册一个监听器,并在选定状态更改时移动它们。这是一个简单的例子。您需要弄清楚当用户检查树根时要做什么 - 我不太清楚您想要的行为(第一棵树应该是空的吗?) - 但这应该足以让您开始。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class MovingCheckedTreeItems extends Application {

@Override
public void start(Stage primaryStage) {
CheckBoxTreeItem<String> uncheckedTreeRoot = new CheckBoxTreeItem<>("Unchecked tree");
uncheckedTreeRoot.setExpanded(true);
TreeView<String> uncheckedTree = new TreeView<>(uncheckedTreeRoot);
uncheckedTree.setCellFactory(CheckBoxTreeCell.forTreeView());

CheckBoxTreeItem<String> checkedTreeRoot = new CheckBoxTreeItem<>("Checked tree");
checkedTreeRoot.setExpanded(true);
TreeView<String> checkedTree = new TreeView<>(checkedTreeRoot);
checkedTree.setCellFactory(CheckBoxTreeCell.forTreeView());

for (int i=0; i<20; i++) {
CheckBoxTreeItem<String> item = new CheckBoxTreeItem<>("Item "+(i+1));
item.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
item.getParent().getChildren().remove(item);
if (isNowSelected) {
// add to checkedTree, will take all sub-nodes with it...
checkedTreeRoot.getChildren().add(item);
} else {
// add to uncheckedTree
uncheckedTreeRoot.getChildren().add(item);
}
});
uncheckedTreeRoot.getChildren().add(item);
}

HBox root = new HBox(5, uncheckedTree, checkedTree);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}

关于java - 复选框状态下的 TreeView 传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26753091/

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