问题
I am using a JavaFX 2 table for some kind of playlist and I want to be able to drag & drop rows in the table, e.g. drag row 3 before row 2, like the drag & drop stuff you know from the playlists in typical media players like e.g. Winamp, AIMP...
Is that possible? Any code samples for that? Thank you very much!
回答1:
try this one :)
@FXML
TableView<String> tableView;
private ObservableList<String> tableContent = FXCollections.observableArrayList();
//...
tableView.setOnMouseClicked(new EventHandler<MouseEvent>() { //click
@Override
public void handle(MouseEvent event) {
if(event.getClickCount()==2){ // double click
String selected = tableView.getSelectionModel().getSelectedItem();
if(selected !=null){
System.out.println("select : "+selected);
...
}
}
}
});
tableView.setOnDragDetected(new EventHandler<MouseEvent>() { //drag
@Override
public void handle(MouseEvent event) {
// drag was detected, start drag-and-drop gesture
String selected = tableView.getSelectionModel().getSelectedItem();
if(selected !=null){
Dragboard db = tableView.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(selected);
db.setContent(content);
event.consume();
}
}
});
tableView.setOnDragOver(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
// data is dragged over the target
Dragboard db = event.getDragboard();
if (event.getDragboard().hasString()){
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
});
tableView.setOnDragDropped(new EventHandler<DragEvent>() {
@Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (event.getDragboard().hasString()) {
String text = db.getString();
tableContent.add(text);
tableView.setItems(tableContent);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
});
来源:https://stackoverflow.com/questions/12353576/drag-drop-in-javafx-table