下面列出了怎么用javafx.scene.control.CheckBoxTreeItem的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void loadTree() {
treeView.setRoot(null);
if (times == null || times.isEmpty()) {
return;
}
try {
CheckBoxTreeItem<ConditionNode> allItem = new CheckBoxTreeItem(
ConditionNode.create(message("AllTime"))
.setTitle(message("AllTime"))
.setCondition("")
);
allItem.setExpanded(true);
treeView.setRoot(allItem);
for (Date time : times) {
String timeString = DateTools.datetimeToString(time);
addTime(timeString);
}
treeView.setSelection();
} catch (Exception e) {
logger.debug(e.toString());
}
}
public void setSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (selectedTitles.contains(node.getTitle())) {
citem.setSelected(true);
return;
} else if (item.isLeaf()) {
return;
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
setSelection(child);
}
} catch (Exception e) {
logger.debug(e.toString());
}
}
public void checkExpanded(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf() || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (citem.isExpanded() && !expandedNodes.contains(node.getTitle())) {
expandedNodes.add(node.getTitle());
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkExpanded(child);
}
} catch (Exception e) {
logger.debug(e.toString());
}
}
@Test
public void selectTreeItemCheckBoxSelectedSelected() {
TreeView<?> treeViewNode = (TreeView<?>) getPrimaryStage().getScene().getRoot().lookup(".tree-view");
CheckBoxTreeItem<?> treeItem = (CheckBoxTreeItem<?>) treeViewNode.getTreeItem(2);
treeItem.setSelected(true);
JSONObject o = new JSONObject();
o.put("select", "/Root node/Child Node 2");
IJavaFXElement item = treeView.findElementByCssSelector(".::select-by-properties('" + o.toString() + "')");
IJavaFXElement cb = item.findElementByCssSelector(".::editor");
cb.marathon_select("Child Node 2:checked");
new Wait("Wait for tree item check box to be selected") {
@Override
public boolean until() {
String selected = cb.getAttribute("selected");
return selected.equals("true");
}
};
}
@Test
public void selectTreeItemCheckBoxSelectedNotSelected() {
TreeView<?> treeViewNode = (TreeView<?>) getPrimaryStage().getScene().getRoot().lookup(".tree-view");
CheckBoxTreeItem<?> treeItem = (CheckBoxTreeItem<?>) treeViewNode.getTreeItem(2);
treeItem.setSelected(true);
JSONObject o = new JSONObject();
o.put("select", "/Root node/Child Node 2");
IJavaFXElement item = treeView.findElementByCssSelector(".::select-by-properties('" + o.toString() + "')");
IJavaFXElement cb = item.findElementByCssSelector(".::editor");
cb.marathon_select("Child Node 2:unchecked");
new Wait("Wait for tree item check box to be deselected") {
@Override
public boolean until() {
String selected = cb.getAttribute("selected");
return selected.equals("false");
}
};
}
public CheckBoxTreeViewSample() {
final CheckBoxTreeItem<String> treeRoot = new CheckBoxTreeItem<String>("Root node");
treeRoot.getChildren().addAll(Arrays.asList(new CheckBoxTreeItem<String>("Child Node 1"),
new CheckBoxTreeItem<String>("Child Node 2"), new CheckBoxTreeItem<String>("Child Node 3")));
treeRoot.getChildren().get(2).getChildren()
.addAll(Arrays.asList(new CheckBoxTreeItem<String>("Child Node 4"), new CheckBoxTreeItem<String>("Child Node 5"),
new CheckBoxTreeItem<String>("Child Node 6"), new CheckBoxTreeItem<String>("Child Node 7"),
new TreeItem<String>("Child Node 8"), new CheckBoxTreeItem<String>("Child Node 9"),
new CheckBoxTreeItem<String>("Child Node 10"), new CheckBoxTreeItem<String>("Child Node 11"),
new CheckBoxTreeItem<String>("Child Node 12")));
final TreeView treeView = new TreeView();
treeView.setCellFactory(CheckBoxTreeCell.forTreeView());
treeView.setShowRoot(true);
treeView.setRoot(treeRoot);
treeRoot.setExpanded(true);
getChildren().add(treeView);
}
@Test
public void select() {
TreeView<?> treeView = (TreeView<?>) getPrimaryStage().getScene().getRoot().lookup(".tree-view");
LoggingRecorder lr = new LoggingRecorder();
Platform.runLater(new Runnable() {
@Override
public void run() {
Point2D point = getPoint(treeView, 1);
RFXTreeView rfxListView = new RFXTreeView(treeView, null, point, lr);
rfxListView.focusGained(rfxListView);
CheckBoxTreeItem<?> treeItem = (CheckBoxTreeItem<?>) treeView.getTreeItem(1);
treeItem.setSelected(true);
rfxListView.focusLost(rfxListView);
}
});
List<Recording> recordings = lr.waitAndGetRecordings(1);
Recording recording = recordings.get(0);
AssertJUnit.assertEquals("recordSelect", recording.getCall());
AssertJUnit.assertEquals("Child Node 1:checked", recording.getParameters()[0]);
}
@Test
public void selectSelectedTreeItemCheckBox() {
TreeView<?> treeView = (TreeView<?>) getPrimaryStage().getScene().getRoot().lookup(".tree-view");
LoggingRecorder lr = new LoggingRecorder();
Platform.runLater(new Runnable() {
@Override
public void run() {
Point2D point = getPoint(treeView, 1);
RFXTreeView rfxListView = new RFXTreeView(treeView, null, point, lr);
CheckBoxTreeItem<?> treeItem = (CheckBoxTreeItem<?>) treeView.getTreeItem(1);
treeItem.setSelected(true);
rfxListView.focusGained(rfxListView);
treeItem.setSelected(false);
rfxListView.focusLost(rfxListView);
}
});
List<Recording> recordings = lr.waitAndGetRecordings(1);
Recording recording = recordings.get(0);
AssertJUnit.assertEquals("recordSelect", recording.getCall());
AssertJUnit.assertEquals("Child Node 1:unchecked", recording.getParameters()[0]);
}
/**
* Native init method.
* Create VUFS folders tree view
* @param location
* @param resources
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
//TODO: replace to getting elements from Repository
CheckBoxTreeItem<String> root = new CheckBoxTreeItem<>("Root");
root.setExpanded(true);
CheckBoxTreeItem<String> folder1 = new CheckBoxTreeItem<>("Folder1");
folder1.getChildren().addAll(
new CheckBoxTreeItem<>("MyFoto"),
new CheckBoxTreeItem<>("OtherFiles")
);
root.getChildren().addAll(
folder1,
new CheckBoxTreeItem<>("Documents"),
new CheckBoxTreeItem<>("WorkFiles"),
new CheckBoxTreeItem<>("Projects"));
// Create the CheckTreeView with the data
final CheckTreeView<String> checkTreeView = new CheckTreeView<>(root);
checkTreeView.getCheckModel().getCheckedItems()
.addListener((ListChangeListener<TreeItem<String>>) c -> {
System.out.println(checkTreeView.getCheckModel().getCheckedItems());
});
checkTreeView.setId("sync-tree-view");
container.getChildren().add(checkTreeView);
}
/**
* Set the selections.
*
* @param values the selected objects.
*/
public void setValue(final Object[] values) {
lipidChoices.getCheckModel().clearChecks();
for (Object lipidClass : values) {
CheckBoxTreeItem<Object> item = classToItemMap.get(lipidClass);
lipidChoices.getCheckModel().check(item);
}
}
/**
* Recursive pre-order traversal of the pin type hierarchy tree. Generated items are added automatically.
*
* @param type
* the current type to add
* @param parent
* the parent tree item to add this one to. <code>null</code> if {@code type} is the root type, in this case the generated tree
* item will be used as root for the tree directly.
* @param tree
* the tree containing the items
*/
private void initPinCheckboxes(PinType type, CheckBoxTreeItem<PinType> parent, CheckTreeView<PinType> tree) {
ImageView image = new ImageView(type.image);
/*
* The only way so set the size of an image relative to the text of the label is to bind its height to a font size. Since tree items don't
* possess a fontProperty (it's hidden behind a cell factory implementation), we have to use the next best labeled node (pinBox in this
* case). This will only work if we don't change any font sizes.
*/
image.fitHeightProperty().bind(Bindings.createDoubleBinding(() -> pinBox.getFont().getSize() * 1.5, pinBox.fontProperty()));
image.setSmooth(true);
image.setPreserveRatio(true);
CheckBoxTreeItem<PinType> ret = new CheckBoxTreeItem<>(type, image);
if (parent == null)
tree.setRoot(ret);
else
parent.getChildren().add(ret);
for (PinType sub : type.getChildren())
initPinCheckboxes(sub, ret, tree);
ret.setExpanded(type.expandedByDefault);
if (type.selectedByDefault) {
pins.visiblePins.add(type);
tree.getCheckModel().check(ret);
}
checkedPins.put(type, ret);
}
public void loadTree() {
clearTree();
try {
CheckBoxTreeItem<ConditionNode> allItem = new CheckBoxTreeItem(
ConditionNode.create(message("AllData"))
.setTitle(message("AllData"))
.setCondition("")
);
allItem.setExpanded(true);
treeView.setRoot(allItem);
treeView.setSelection();
} catch (Exception e) {
logger.debug(e.toString());
}
}
protected boolean loaded(TreeItem item) {
if (item == null || item.isLeaf()) {
return true;
}
Object child = item.getChildren().get(0);
return child instanceof CheckBoxTreeItem;
}
public void checkSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (citem.isSelected()) {
if (finalConditions == null || finalConditions.isBlank()) {
if (node.getCondition() == null || node.getCondition().isBlank()) {
finalConditions = "";
} else {
finalConditions = " ( " + node.getCondition() + ") ";
}
} else {
if (node.getCondition() != null && !node.getCondition().isBlank()) {
finalConditions += " OR ( " + node.getCondition() + " ) ";
}
}
if (finalTitle == null || finalTitle.isBlank()) {
finalTitle = "\"" + node.getTitle() + "\"";
} else {
finalTitle += " + \"" + node.getTitle() + "\"";
}
if (!selectedTitles.contains(node.getTitle())) {
selectedTitles.add(node.getTitle());
}
return;
} else if (item.isLeaf() || !citem.isIndeterminate()) {
return;
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkSelection(child);
}
} catch (Exception e) {
logger.debug(e.toString());
}
}
public TreeViewSample() {
String dir = "./src";
final CheckBoxTreeItem<File> treeRoot = buildRoot(dir);
treeView = new TreeView<File>();
treeView.setCellFactory(CheckBoxTreeCell.<File> forTreeView());
treeView.setShowRoot(true);
treeView.setRoot(treeRoot);
treeRoot.setExpanded(true);
getChildren().add(treeView);
}
private CheckBoxTreeItem<File> buildNode(File file) {
CheckBoxTreeItem<File> node = new CheckBoxTreeItem<File>(file);
if (file.isDirectory()) {
ObservableList<TreeItem<File>> children = node.getChildren();
File[] listFiles = file.listFiles();
for (File f : listFiles) {
children.add(buildNode(f));
}
}
return node;
}
public TreeTableEntry(String name, TableEntry tableEntry, TreeTableEntry parent) {
this.name = name;
this.tableEntry = tableEntry;
if (tableEntry == null) {
this.folder = true;
} else {
((SingleListenerBooleanProperty) tableEntry.selectedProperty()).forceAddListener(tableEntrySelectedChangeListener_1);
}
if (parent != null) {
this.parent = parent;
this.parent.children.put(name, this);
this.parentCBTI = parent.cbti;
}
this.children = new HashMap<>();
this.cbti = new CheckBoxTreeItem<>(this);
this.cbti.selectedProperty().bindBidirectional(selected);
this.cbti.indeterminateProperty().bindBidirectional(indeterminate);
selected.set(true);
if (!folder && !tableEntry.readOnlyProperty().get()) {
((SingleListenerBooleanProperty) tableEntry.selectedProperty()).forceAddListener(tableEntrySelectedChangeListener_2);
this.cbti.selectedProperty().addListener(cbtiSelectedChangeListener);
}
}
@Override
public void handle(TreeModificationEvent<PathItem> arg0) {
if (arg0 != null && arg0.getSource() != null) {
if (arg0.getSource() instanceof CheckBoxTreeItem) {
@SuppressWarnings("unchecked")
CheckBoxTreeItem<PathItem> source = (CheckBoxTreeItem<PathItem>) arg0.getSource();
PathItem pathItem = source.getValue();
if (pathItem != null) {
Path path = pathItem.getPath();
FileInfo file = new FileInfo(pathItem);
if (source.isSelected()) {
logger.trace("Add {} to SYNC", path);
getSynchronization().getToSynchronize().add(file);
getSynchronization().getToDesynchronize().remove(file);
} else if (!source.isIndeterminate()) {
logger.trace("Remove {} from SYNC", path);
getSynchronization().getToSynchronize().remove(file);
getSynchronization().getToDesynchronize().add(file);
}
arg0.consume();
}
}
}
}
/**
* Create the component.
*
* @param theChoices the choices available to the user.
*/
public LipidClassComponent(final Object[] theChoices) {
// setBorder(BorderFactory.createEmptyBorder(0, 9, 0, 0));
// Don't show the root item
lipidChoices.setShowRoot(false);
// Load all lipid classes
LipidCoreClasses coreClass = null;
LipidMainClasses mainClass = null;
CheckBoxTreeItem<Object> coreClassItem = null;
CheckBoxTreeItem<Object> mainClassItem = null;
CheckBoxTreeItem<Object> classItem = null;
for (LipidClasses lipidClass : LipidClasses.values()) {
if (lipidClass.getCoreClass() != coreClass) {
coreClassItem = new CheckBoxTreeItem<>(lipidClass.getCoreClass());
coreClassItem.setExpanded(true);
coreClass = lipidClass.getCoreClass();
rootItem.getChildren().add(coreClassItem);
}
if (lipidClass.getMainClass() != mainClass) {
mainClassItem = new CheckBoxTreeItem<>(lipidClass.getMainClass());
mainClassItem.setExpanded(true);
mainClass = lipidClass.getMainClass();
coreClassItem.getChildren().add(mainClassItem);
}
classItem = new CheckBoxTreeItem<>(lipidClass);
classToItemMap.put(lipidClass, classItem);
mainClassItem.getChildren().add(classItem);
}
setLeft(lipidChoices);
// Add buttons.
buttonsPanel.getChildren().addAll(selectAllButton, selectNoneButton);
setCenter(buttonsPanel);
selectAllButton.setTooltip(new Tooltip("Select all choices"));
selectAllButton.setOnAction(e -> {
lipidChoices.getSelectionModel().selectAll();
});
selectNoneButton.setTooltip(new Tooltip("Clear all selections"));
selectNoneButton.setOnAction(e -> {
lipidChoices.getSelectionModel().clearSelection();
});
}
@Override
public void loadTree() {
if (datasets == null || datasets.isEmpty()) {
return;
}
try {
CheckBoxTreeItem<ConditionNode> allItem = new CheckBoxTreeItem(
ConditionNode.create(message("AllSources"))
.setTitle(message("AllSources"))
.setCondition("")
);
allItem.setExpanded(true);
treeView.setRoot(allItem);
for (String dataset : datasets) {
CheckBoxTreeItem<ConditionNode> datasetItem = new CheckBoxTreeItem(
ConditionNode.create(dataset)
.setTitle(dataset)
.setCondition(" data_set='" + dataset.replaceAll("'", "''") + "' ")
);
datasetItem.setExpanded(true);
allItem.getChildren().add(datasetItem);
CheckBoxTreeItem<ConditionNode> pItem = new CheckBoxTreeItem(
ConditionNode.create(message("PredefinedData"))
.setTitle(dataset + " - " + message("PredefinedData"))
.setCondition(" data_set='" + dataset.replaceAll("'", "''")
+ "' AND source=" + EpidemicReport.PredefinedData() + " ")
);
datasetItem.getChildren().add(pItem);
CheckBoxTreeItem<ConditionNode> iItem = new CheckBoxTreeItem(
ConditionNode.create(message("InputtedData"))
.setTitle(dataset + " - " + message("InputtedData"))
.setCondition(" data_set='" + dataset.replaceAll("'", "''")
+ "' AND source=" + EpidemicReport.InputtedData() + " ")
);
datasetItem.getChildren().add(iItem);
CheckBoxTreeItem<ConditionNode> fItem = new CheckBoxTreeItem(
ConditionNode.create(message("FilledData"))
.setTitle(dataset + " - " + message("FilledData"))
.setCondition(" data_set='" + dataset.replaceAll("'", "''")
+ "' AND source=" + EpidemicReport.FilledData() + " ")
);
datasetItem.getChildren().add(fItem);
CheckBoxTreeItem<ConditionNode> sItem = new CheckBoxTreeItem(
ConditionNode.create(message("StatisticData"))
.setTitle(dataset + " - " + message("StatisticData"))
.setCondition(" data_set='" + dataset.replaceAll("'", "''")
+ "' AND source=" + EpidemicReport.StatisticData() + " ")
);
datasetItem.getChildren().add(sItem);
}
treeView.setSelection();
} catch (Exception e) {
logger.debug(e.toString());
}
}
protected void addNodes(CheckBoxTreeItem<ConditionNode> parent, List<GeographyCode> codes,
List<Long> haveChildren, List<Integer> haveLevels) {
if (parent == null || parent.getValue() == null
|| codes == null || codes.isEmpty()) {
return;
}
ConditionNode parantNode = parent.getValue();
GeographyCode parantCode = parantNode.getCode();
GeographyCodeLevel parentLevel = parantCode == null ? null : parantCode.getLevelCode();
String prefix = parantNode.getTitle() != null
? (message("AllLocations").equals(parantNode.getTitle()) ? "" : parantNode.getTitle() + " - ")
: (parantCode == null ? "" : parantCode.getFullName() + " - ");
if (parantCode != null && parentLevel != null) {
CheckBoxTreeItem<ConditionNode> valueItem = new CheckBoxTreeItem(
ConditionNode.create(message("Self"))
.setTitle((prefix.isBlank() ? message("Earth") + " - " : prefix) + message("Self"))
.setCondition("level=" + parentLevel.getLevel()
+ " AND Geography_Code.gcid=" + parantCode.getGcid())
);
parent.getChildren().add(valueItem);
CheckBoxTreeItem<ConditionNode> predefinedItem = new CheckBoxTreeItem(
ConditionNode.create(message("PredefinedData"))
.setTitle(prefix + message("PredefinedData"))
.setCondition((parantCode.getGcid() == 1 ? ""
: parentLevel.getKey() + "=" + parantCode.getGcid() + " AND ")
+ " predefined=1")
);
parent.getChildren().add(predefinedItem);
CheckBoxTreeItem<ConditionNode> inputtedItem = new CheckBoxTreeItem(
ConditionNode.create(message("InputtedData"))
.setTitle(prefix + message("InputtedData"))
.setCondition((parantCode.getGcid() == 1 ? ""
: parentLevel.getKey() + "=" + parantCode.getGcid() + " AND ")
+ " predefined<>1")
);
parent.getChildren().add(inputtedItem);
if (haveLevels != null) {
for (int levelValue : haveLevels) {
GeographyCodeLevel level = new GeographyCodeLevel(levelValue);
CheckBoxTreeItem<ConditionNode> levelItem = new CheckBoxTreeItem(
ConditionNode.create(level.getName())
.setTitle(prefix + level.getName())
.setCondition("level=" + levelValue
+ (parantCode.getGcid() == 1 ? ""
: " AND " + parentLevel.getKey() + "=" + parantCode.getGcid()))
);
parent.getChildren().add(levelItem);
}
}
}
for (GeographyCode code : codes) {
long codeid = code.getGcid();
GeographyCodeLevel codeLevel = code.getLevelCode();
CheckBoxTreeItem<ConditionNode> codeItem = new CheckBoxTreeItem(
ConditionNode.create(code.getName())
.setCode(code)
.setTitle(prefix + code.getName())
.setCondition(codeLevel.getKey() + "=" + codeid)
);
parent.getChildren().add(codeItem);
if (haveChildren != null && haveChildren.contains(codeid)) {
TreeItem<ConditionNode> dummyItem = new TreeItem("Loading");
codeItem.getChildren().add(dummyItem);
codeItem.expandedProperty().addListener(
(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) -> {
if (newVal && !codeItem.isLeaf() && !loaded(codeItem)) {
nodeTree(codeItem, code);
}
});
codeItem.setExpanded(treeView.getExpandedNodes().contains(prefix + code.getName()));
}
}
if (parent.isSelected()) {
for (TreeItem<ConditionNode> child : parent.getChildren()) {
((CheckBoxTreeItem<ConditionNode>) child).setSelected(true);
}
}
}
protected void nodeTree(CheckBoxTreeItem<ConditionNode> parent, GeographyCode code) {
if (parent == null || code == null) {
return;
}
parent.getChildren().clear();
synchronized (this) {
if (task != null) {
return;
}
task = new SingletonTask<Void>() {
private List<GeographyCode> nodes;
private List<Long> haveChildren;
private List<Integer> haveLevels;
@Override
protected boolean handle() {
try ( Connection conn = DriverManager.getConnection(protocol + dbHome() + login)) {
conn.setReadOnly(true);
GeographyCodeLevel level = code.getLevelCode();
int codeLevel = level.getLevel();
if (level.getKey() == null || codeLevel < 2 || codeLevel > 8) {
return false;
}
if (loading != null) {
loading.setInfo(message("Loading") + " " + level.getName()
+ " " + code.getName());
}
nodes = TableGeographyCode.queryChildren(conn, code.getGcid());
if (nodes == null || nodes.isEmpty()) {
return false;
}
if (loading != null) {
loading.setInfo(message("CheckingLeafNodes"));
}
haveChildren = TableGeographyCode.haveChildren(conn, nodes);
if (loading != null) {
loading.setInfo(message("LoadingLevels"));
}
haveLevels = new ArrayList();
for (int i = codeLevel + 1; i <= 9; i++) {
String sql = "SELECT gcid FROM Geography_Code WHERE "
+ " level=" + i + " AND "
+ level.getKey() + "=" + code.getGcid()
+ " OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY";
try ( ResultSet results = conn.createStatement().executeQuery(sql)) {
if (results.next()) {
haveLevels.add(i);
}
}
}
return true;
} catch (Exception e) {
error = e.toString();
return false;
}
}
@Override
protected void whenSucceeded() {
addNodes(parent, nodes, haveChildren, haveLevels);
}
};
if (getUserController() != null) {
loading = getUserController().openHandlingStage(task, Modality.WINDOW_MODAL);
} else {
loading = openHandlingStage(task, Modality.WINDOW_MODAL);
}
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
}
public void selectAll() {
CheckBoxTreeItem<ConditionNode> root = (CheckBoxTreeItem<ConditionNode>) getRoot();
root.setSelected(true);
}
public void selectNone() {
CheckBoxTreeItem<ConditionNode> root = (CheckBoxTreeItem<ConditionNode>) getRoot();
root.setSelected(false);
}
private CheckBoxTreeItem<File> buildRoot(String dir) {
return buildNode(new File(dir));
}
public CheckBoxTreeItem<?> getRpcDhild() {
return rpcDhild;
}
public void setRpcDhild(CheckBoxTreeItem<?> rpcDhild) {
this.rpcDhild = rpcDhild;
}