Created
April 10, 2024 07:34
-
-
Save johannest/a0287403604fe5186781ce3ee9240580 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.vaadin.flow.component.AttachEvent; | |
import com.vaadin.flow.component.Component; | |
import com.vaadin.flow.component.dnd.*; | |
import com.vaadin.flow.component.grid.Grid; | |
import com.vaadin.flow.component.html.Div; | |
import com.vaadin.flow.component.orderedlayout.VerticalLayout; | |
import com.vaadin.flow.router.Route; | |
import java.time.LocalDate; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
@Route | |
public class DragAndDropReorderComponents extends VerticalLayout { | |
public MainView() { | |
Div box1 = new Div(createGrid(1)); | |
Div box2 = new Div(createGrid(2)); | |
Div box3 = new Div(createGrid(3)); | |
createDragSource(this, box1); | |
createDragSource(this, box2); | |
createDragSource(this, box3); | |
createDropTarget(box1); | |
createDropTarget(box2); | |
createDropTarget(box3); | |
add(box1, box2, box3); | |
} | |
private static void createDragSource(VerticalLayout layout, Div box) { | |
DragSource<Div> dragSource = DragSource.create(box); | |
dragSource.setEffectAllowed(EffectAllowed.MOVE); | |
dragSource.setDragData(box); | |
} | |
private void createDropTarget(Div box) { | |
DropTarget<Div> dropTarget = DropTarget.create(box); | |
dropTarget.setDropEffect(DropEffect.MOVE); | |
dropTarget.setActive(true); | |
dropTarget.addDropListener(dropEvent -> { | |
reOrderLayout(box, dropEvent); | |
}); | |
} | |
private void reOrderLayout(Div targetComponent, DropEvent<Div> dropEvent) { | |
Component draggedComponent = dropEvent.getDragSourceComponent().get(); | |
int newIndex = getIndex(targetComponent); | |
remove(draggedComponent); | |
addComponentAtIndex(newIndex, draggedComponent); | |
} | |
private int getIndex(Component component) { | |
List<Component> childs = getChildren().collect(Collectors.toList()); | |
for (int i=0; i<childs.size(); i++) { | |
if (childs.get(i) == component) { | |
return i; | |
} | |
} | |
return 0; | |
} | |
private Grid<Person> createGrid(int index) { | |
Grid<Person> grid = new Grid<>(Person.class, false); | |
grid.addColumn(Person::getName).setHeader("Name"); | |
grid.addColumn(Person::getDate).setHeader("Date"); | |
grid.setItems(new Person(index, "Foo "+index, true)); | |
grid.setHeight("150px"); | |
grid.setWidth("350px"); | |
return grid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment