以下代码用于显示树视图和打印输出用户选择的值。 我想在ChangeLisner方法的参数中打印出“OK”,这意味着对象“oval”的值相同。
我该怎么办?
我参考以下网址
http://blog.professional-webworkx.de/javafx-get-selecteditem-of-treeview/
我将代码添加如下:
if("TreeItem [ value: SubItem ]".equals(oldVal)){System.out.println("YES");}
else{System.out.println("NO");}"
System.out.println的结果如下:
TreeItem [value:SubItem]
NO
package app;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.Scene;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
public class App extends Application{
@Override
public void start(Stage stage) throws Exception {
TreeItem<String> item = new TreeItem<String>("root");
final TreeView<String> treeView = new TreeView<String>(item);
for(int i=0; i<10; i++) {
item.getChildren().add(new TreeItem<String>("Item" + i));
if(i%5==0) {
TreeItem<String> subItem = new TreeItem<String>("SubItem");
item.getChildren().add(subItem);
subItem.setExpanded(true);
for(int j=0; j<10; j++) {
subItem.getChildren().add(new TreeItem<String>("SubsubItem" + i));
}
}
}
treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldVal, Object newVal) {
System.out.println(oldVal);// + " neuer: " + newVal);
if("TreeItem [ value: SubItem ]".equals(oldVal)){System.out.println("YES");}
else{System.out.println("NO");}
}
});
stage.setTitle("TreeView");
stage.setScene(new Scene(treeView, 640, 480));
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
答案 0 :(得分:0)
不要比较树项的toString
;比较它的价值。 (不使用原始类型:正确键入所有变量和匿名类等。)
treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
@Override
public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldItem, TreeItem<String> newItem) {
System.out.println(oldItem.getValue());// + " neuer: " + newVal);
if(oldItem != null && "SubItem".equals(oldItem.getValue())){
System.out.println("YES");
} else{
System.out.println("NO");
}
}
});
当然,使用lambda表达式(并利用Java 8类型推断)更清晰:
treeView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldItem, newItem) -> {
System.out.println(oldItem.getValue());// + " neuer: " + newVal);
if(oldItem != null && "SubItem".equals(oldItem.getValue())){
System.out.println("YES");
} else{
System.out.println("NO");
}
}
);