在 javafx-2 ListView 中,我注意到 getSelectedIndices 中有一个奇怪的(但可以解决的)行为。
getSelectedIndices 属性(SelectionModel 的)是一个可观察的列表,如果允许多选,则该列表应该包含选定的项目或选定的项目。
但是如果我添加一个项目,选择它然后删除它,您可能会认为选择不会包含任何项目,但实际上它确实包含一个项目并且恰好是 -1。
这是显示这一事实的最简单的代码。
public class T01 extends Application {
public static void main (String [] args) { launch(args);}
ListView<String> listView;
//just create the controls, that is a BorderPane with a ListView in its center
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane borderPane = new BorderPane();
listView = new ListView();
borderPane.setCenter(listView);
primaryStage.setScene(new Scene(borderPane));
primaryStage.show();
doTest();
}
//doTest: add an item, select it, remove it and inspect the selection model again
public void doTest() {
System.out.println("A) before adding items");
printSelectedItem(listView);
listView.getItems().add("first");
listView.getSelectionModel().select(0);
System.out.println("B) added an item and selected");
printSelectedItem(listView);
listView.getItems().remove(0);
System.out.println("C) removed the item");
printSelectedItem(listView);
}
public void printSelectedItem(ListView listView) {
ObservableList<Integer> list = listView.getSelectionModel().getSelectedIndices();
System.out.println("The selectedIndices property contains: " + list.size() + " element(s):");
for(int i=0; i<list.size(); i++) { System.out.println(i + ")" + list.get(i)); }
}
}
这是我的输出:
run:
A) before adding items
The selectedIndices property contains: 0 element(s):
B) added an item and selected
The selectedIndices property contains: 1 element(s):
0)0
C) removed the item
The selectedIndices property contains: 1 element(s):
0)-1
案例“C”显示“意外”行为。也许记录在某处?
环境信息:javafx.runtime.version:2.2.3-b05 java.runtime.version:1.6.0_29-b11 os.name:Windows 7 os.version:6.1