我正在尝试使用拖放功能将项目从一个ListView移动到另一个ListView。在目标的setDragDropped方法上,我放了这个简单的代码(listaOrigen是dragAndDrop开始的源listView:
System.out.println("items size before moving = " + items.size());
List<EpisodioUIBean> uiBeans = listaOrigen.getSelectionModel().getSelectedItems();
System.out.println("beans size to move = " + uiBeans.size());
items.addAll(uiBeans);
System.out.println("items size after moving = " + items.size());
System.out.println("items in the source list before moving = " + listaOrigen.getItems().size());
listaOrigen.getItems().removeAll(uiBeans);
System.out.println("items in the source list after moving " + uiBeans.size() + " items = " + listaOrigen.getItems().size());
上面这些行的恼人输出是
items size before moving = 10
beans size to move = 1
items size after moving = 11
items in the source list before moving = 172
items in the source list after moving 1 items = 169
这怎么可能发生?
我可以使用这个可运行的程序重现结果:
package tree;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ListViews extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("ListViews");
List<String> list = Arrays.asList("Hola", "Hola", "Hallo", "Hola");
ListView<String> listView1 = new ListView<>(FXCollections.observableArrayList(list));
ListView<String> listView2 = new ListView<>();
VBox root = new VBox();
Button b = new Button("Move selected Items");
b.setOnAction(evt -> {
List<String> strings = listView1.getSelectionModel().getSelectedItems();
listView2.getItems().addAll(strings);
listView1.getItems().removeAll(strings);
});
root.getChildren().add(b);
root.getChildren().add(listView1);
root.getChildren().add(listView2);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
只需选择第一个“Hola”项目,然后单击按钮。所有三个“Hola”项目都从第一个ListView消失了!