在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