javafx - Drag and drop item into TableView, between existing rows -
table contains following rows (one column example):
a b c
i'm trying figure out how drag item it, , have placed between existing rows b , c.
i able drag-and-drop results in item added @ end of table can't figure out how place in between rows, based on release mouse button.
create rowfactory
producing tablerow
s accept gesture , decide mouse position, whether add item before or after row:
@override public void start(stage primarystage) { tableview<item> table = new tableview<>(); button button = new button("a"); // d&d source providing next char button.setondragdetected(evt -> { dragboard db = button.startdraganddrop(transfermode.move); clipboardcontent content = new clipboardcontent(); content.putstring(button.gettext()); db.setcontent(content); }); button.setondragdone(evt -> { if (evt.isaccepted()) { // next char button.settext(character.tostring((char) (button.gettext().charat(0) + 1))); } }); // accept empty table table.setondragover(evt -> { if (evt.getdragboard().hasstring()) { evt.accepttransfermodes(transfermode.copy_or_move); } evt.consume(); }); table.setondragdropped(evt -> { dragboard db = evt.getdragboard(); if (db.hasstring()) { table.getitems().add(new item(db.getstring())); evt.setdropcompleted(true); } evt.consume(); }); tablecolumn<item, string> col = new tablecolumn<>("value"); col.setcellvaluefactory(new propertyvaluefactory<>("value")); table.getcolumns().add(col); // let rows accept drop table.setrowfactory(tv -> { tablerow<item> row = new tablerow(); row.setondragover(evt -> { if (evt.getdragboard().hasstring()) { evt.accepttransfermodes(transfermode.copy_or_move); } evt.consume(); }); row.setondragdropped(evt -> { dragboard db = evt.getdragboard(); if (db.hasstring()) { item item = new item(db.getstring()); if (row.isempty()) { // row empty (at end -> append item) table.getitems().add(item); } else { // decide based on drop position whether add element before or after int offset = evt.gety() > row.getheight() / 2 ? 1 : 0; table.getitems().add(row.getindex() + offset, item); evt.setdropcompleted(true); } } evt.consume(); }); return row; }); scene scene = new scene(new vbox(button, table)); primarystage.setscene(scene); primarystage.show(); }
public class item { public item() { } public item(string value) { this.value.set(value); } private final stringproperty value = new simplestringproperty(); public string getvalue() { return value.get(); } public void setvalue(string val) { value.set(val); } public stringproperty valueproperty() { return value; } }
Comments
Post a Comment