下面给出的示例是可编辑的fall-tree。
public class Main extends Application
{
private BorderPane border;
TreeItem<String> tree;
TreeView<String> treeView;
@Override
public void start(Stage primaryStage)
{
border = new BorderPane();
Scene scene = new Scene(border,750,500);
primaryStage.setTitle("BorderPane");
primaryStage.setScene(scene);
primaryStage.show();
tree = new TreeItem<String>("Library");
TreeItem<String> item1 = new TreeItem<String>("Module");
TreeItem<String> item1Child = new TreeItem<String>("MX");
item1.getChildren().add(item1Child);
TreeItem<String> item2 = new TreeItem<String>("Unite");
TreeItem<String> item2Child = new TreeItem<String>("UX");
item2.getChildren().add(item2Child);
item2.setExpanded(true);
TreeItem<String> item3 = new TreeItem<String>("Translate");
TreeItem<String> item3Child = new TreeItem<String>("TX");
item3.getChildren().add(item3Child);
TreeItem<String> item4 = new TreeItem<String>("Rotate");
TreeItem<String> item4Child = new TreeItem<String>("Rx");
item4.getChildren().add(item4Child);
tree.setExpanded(true);
tree.getChildren().addAll(item1,item2,item3,item4);
treeView = new TreeView<String>(tree);
treeView.setEditable(true);
treeView.setCellFactory(TextFieldTreeCell.forTreeView());
VBox vbox =new VBox(2);
vbox.setPadding(new Insets(5));
VBox.setVgrow(treeView, Priority.ALWAYS);
vbox.getChildren().addAll(new Text("Fall Tree"),treeView);
HBox hb = new HBox();
VBox rightPane = getrightPane();
hb.setSpacing(20);
hb.getChildren().addAll(vbox,rightPane);
border.setCenter(hb);
}
private VBox getrightPane() {
VBox vb = new VBox(30);
vb.setPadding(new Insets(10));
HBox h1 = new HBox(7);
h1.getChildren().addAll(new Label("X:"), new TextField());
HBox box = new HBox(20);
Rectangle rect1 = new Rectangle(150,150);
rect1.setFill(null);
rect1.setStroke(Color.BLACK);
box.getChildren().addAll(rect1);
box.setAlignment(Pos.BOTTOM_CENTER);
vb.getChildren().addAll(h1,box);
return vb;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
正如在评论部分可以看到的那样,应用了一个监听器,但它只在分支和叶子文本上检查文本。
我的问题是如何将getrightPane()整体指定为唯一一个叶子的监听器(例如MX)。应用时,其他叶子不应显示getrightPane()。
请帮我指定getrightPane()作为只有一个选定的叶子/分支的监听器。
谢谢。
答案 0 :(得分:2)
试试这个
VBox rightPane = new VBox();
treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (newValue == item1Child) {
rightPane.getChildren().add(getrightPane());
} else {
int i = rightPane.getChildren().size();
if (i > 0) {
rightPane.getChildren().remove(0);
}
}
}
});
答案 1 :(得分:1)
你应该能够做到,例如:
treeView.getSelectionModel().selectedItemProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == item1Child) {
System.out.println("MX selected");
// do whatever you need here....
}
});