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