horizo​​ntalLayout中表之间的拖放不起作用

时间:2016-10-16 22:03:10

标签: java drag-and-drop vaadin

我在Vaadin有3张桌子:

3 Tables within a horizontal Layout

我现在的问题是Drag&掉落不起作用。我的代码如下:

@Theme("valo")
@SpringView(name = TaskboardView.VIEW_NAME)
public class TaskboardView extends VerticalLayout implements View {

private enum TableType {
    DONE, PROGRESS, OPEN;
}

private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(TaskboardView.class);
public static final String VIEW_NAME = "taskboard";

// Components:
private SprintController sprintController = new SprintController();
private TaskController taskController = new TaskController();
private Sprint sprint;
private Set<Task> allTasks;
private List<Task> openTasks = new ArrayList<Task>();
private List<Task> inProgressTasks = new ArrayList<Task>();
private List<Task> doneTasks = new ArrayList<Task>();

// UI Components:
private Table openTable = new Table("Open Tasks:");
private int openTableId = 1;
private Table inProgressTable = new Table("Tasks in Progress");
private int inProgressTableId = 1;
private Table doneTable = new Table("Done Tasks");
private int doneTableId = 1;
private TextField sprintName = new TextField();
private OpenTableDropHandler openTableDropHandler = new OpenTableDropHandler();
private InProgressTableDropHandler inProgressTableDropHandler = new InProgressTableDropHandler();
DoneTableHandler doneTableHandler = new DoneTableHandler();

@PostConstruct
void init() {
    logger.info("Initializing Taskboard View...");
    try {
        this.sprint = sprintController.getActiveSprint();
        this.allTasks = sprintController.getTasksInSprint(this.sprint.getId().intValue());
        sortSprintTasks(this.allTasks);
        this.sprintName.setNullRepresentation("-- No active Sprint found --");
        this.sprintName.setValue(this.sprint.getSprintName());
        this.sprintName.setWidth("800px");
        this.sprintName.setReadOnly(true);
        this.sprintName.addStyleName("align-center"); // sets Allignment of
                                                        // the textfield!!!

    } catch (NoActiveSprintReceivedException | NoSprintsExistException | IOException e) {
        logger.error("Something went wrong initializing active Sprint. The taskboard can't be displayed.", e);
        Notification.show("No Active Sprint found!", Notification.Type.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    } catch (TaskCanNotBeAllocatedException e) {
        logger.error("Task of sprint couldn't be allocated to an status.", e);
        Notification.show("Error! \n \n Task of sprint couldn't be allocated to an status.",
                Notification.Type.ERROR_MESSAGE);
        e.printStackTrace();
        return;
    }
    // Layout for Sprint Name:
    VerticalLayout headLayout = new VerticalLayout();
    headLayout.setSpacing(true);
    headLayout.setSizeFull();
    ;
    headLayout.setMargin(true);
    headLayout.addComponent(this.sprintName);
    headLayout.setComponentAlignment(this.sprintName, Alignment.MIDDLE_CENTER);

    setSizeFull();
    setSpacing(true);
    setMargin(true);
    // Layout:
    VerticalLayout verticalLayout = new VerticalLayout();
    verticalLayout.setSpacing(true);

    // Layout for Board:
    HorizontalLayout taskBoardLayout = new HorizontalLayout();
    taskBoardLayout.setSizeUndefined();
    taskBoardLayout.setSpacing(true);
    taskBoardLayout.setMargin(true);

    // Adding to HorizontalLayout(TaskBoadLayout)
    try {
        initTable(this.openTable, TableType.OPEN);
        initTable(this.inProgressTable, TableType.PROGRESS);
        initTable(this.doneTable, TableType.DONE);
    } catch (IOException e) {
        logger.error("Something went wrong initizalizing Tables.");
        Notification.show("Error! \n \n Couldn't initialize tables.", Notification.Type.ERROR_MESSAGE);
        return;
    }

    taskBoardLayout.addComponent(openTable);
    taskBoardLayout.addComponent(inProgressTable);
    taskBoardLayout.addComponent(doneTable);

    // Adding to VerticalLayout (MainLayout)
    verticalLayout.addComponent(headLayout);
    verticalLayout.addComponent(taskBoardLayout);
    verticalLayout.setComponentAlignment(taskBoardLayout, Alignment.MIDDLE_CENTER);
    addComponent(verticalLayout);
}

/**
 * Sorts the tasks of the sprint to the required lists like open, in
 * Progress, done.
 *
 * @param tasks
 * @throws TaskCanNotBeAllocatedException
 */
private void sortSprintTasks(Set<Task> tasks) throws TaskCanNotBeAllocatedException {
    logger.info("sortSprintTask(Set<Task>tasks): Sorting Tasks to the required lists...");
    for (Task t : tasks) {
        logger.info("Checking Sprint Status of Task >>>> " + t.getHeadLine() + " <<<<");
        logger.info("Status: " + t.getStatus());
        if (t.getStatus().equals(WorkflowStatusConfigurator.open)) {
            this.openTasks.add(t);
        } else if (t.getStatus().equals(WorkflowStatusConfigurator.inProgress)) {
            this.inProgressTasks.add(t);
        } else if (t.getStatus().equals(WorkflowStatusConfigurator.done)) {
            this.doneTasks.add(t);
        } else {
            throw new TaskCanNotBeAllocatedException(
                    "Task can't be allocated to a sprint status: " + WorkflowStatusConfigurator.open + ", "
                            + WorkflowStatusConfigurator.inProgress + ", " + WorkflowStatusConfigurator.done + ".");
        }

    }
}

@Override
public void enter(ViewChangeEvent event) {
    // TODO Auto-generated method stub

}

/**
 * Creates the tables depending on the type parameter
 *
 * @param table
 * @param type
 * @throws IOException
 * @throws ClientProtocolException
 */
private void initTable(Table table, TableType type) throws ClientProtocolException, IOException {
    table.setSelectable(true);
    table.setImmediate(true);
    table.setDragMode(TableDragMode.ROW);
    table.addContainerProperty("ID", Long.class, null);
    table.setColumnWidth("ID", 50);
    table.addContainerProperty("Headline", String.class, null);
    table.setColumnWidth("Headline", 300);
    table.addContainerProperty("Task-Type", String.class, null);
    table.setColumnWidth("Task-Type", 120);
    table.addContainerProperty("Assignee", String.class, null);
    table.setColumnWidth("Assignee", 100);

    if (type.equals(TableType.OPEN) && this.openTasks.size() > 0) {
        logger.info("Loading values of Open Tasks Table...");
        table.setDropHandler(this.openTableDropHandler);
        for (Task t : this.openTasks) {
            String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
            table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.openTableId);
            this.openTableId++;
        }
        return;

    }

    if (type.equals(TableType.PROGRESS) && this.inProgressTasks.size() > 0) {
        logger.info("Loading values of Progress Tasks Table...");
        table.setDropHandler(this.inProgressTableDropHandler);
        for (Task t : this.inProgressTasks) {
            String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
            table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.inProgressTableId);
            this.inProgressTableId++;
        }
        return;
    }

    if (type.equals(TableType.DONE) && this.doneTasks.size() > 0) {
        logger.info("Loading values of Done Tasks Table...");
        table.setDropHandler(this.doneTableHandler);
        for (Task t : this.doneTasks) {
            String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
            table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.doneTableId);
            this.doneTableId++;
        }
        return;
    }
}

private int giveEncreasedAvailableTableId(TableType tableType) {
    if(tableType.equals(TableType.OPEN)){
        this.openTableId++;
        return this.openTableId;
    }else if(tableType.equals(TableType.PROGRESS)){
        this.inProgressTableId++;
        return this.inProgressTableId;
    }else if(tableType.equals(TableType.DONE)){
        this.doneTableId++;
        return this.doneTableId;
    }else{
        return -1;
    }

}

private class OpenTableDropHandler implements DropHandler{

    private static final long serialVersionUID = 1L;
    private final Logger logger = LoggerFactory.getLogger(OpenTableDropHandler.class);

    @Override
    public void drop(DragAndDropEvent event) {
        // Wrapper for the object that is dragged
        logger.info("Received Drag and Drop Event from OpenTable...");
        DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
         AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
        Object itemId = t.getItemId();
        Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
        try {
            Task taskToAdd = taskController.getById(id.intValue());
            String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
            if ( t.getSourceComponent() != openTable && dropData.getTarget().equals(inProgressTable)) {
                logger.info("Preparing Task Update to InProgress...");
                openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
                openTasks.add(taskToAdd);
                inProgressTable.removeItem(itemId);
                inProgressTasks.remove(taskToAdd);
            }else if(t.getSourceComponent() != openTable && dropData.getTarget().equals(doneTable)){
                logger.info("Preparing Task Update to Done...");
                openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
                openTasks.add(taskToAdd);
                doneTable.removeItem(itemId);
                doneTasks.remove(taskToAdd);
            }else{
                logger.info("Do nothing...");
                return;
            }
            taskToAdd.setStatus(WorkflowStatusConfigurator.open);
            logger.info("Sending updates of taskboard to webservice...");
            HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
            MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
   //               HttpResponse authorResponse =      taskController.setAuthorInTask(taskToAdd.getAuthor().getId().intValue(),
 //                     taskToAdd.getId().intValue());
    //              HttpResponse assigneeResponse =    taskController.setAssigneeInTask(taskToAdd.getAssignee().getId().intValue(),
 //                     taskToAdd.getId().intValue());

        } catch (ClientProtocolException e) {

            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        } catch (IOException e) {
            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        }

    }

    @Override
    public AcceptCriterion getAcceptCriterion() {
        return AcceptAll.get();
    }

}

private class InProgressTableDropHandler implements DropHandler{


    private static final long serialVersionUID = 1L;
    private final Logger logger = LoggerFactory.getLogger(InProgressTableDropHandler.class);

    @Override
    public void drop(DragAndDropEvent event) {
        // Wrapper for the object that is dragged
        logger.info("Received Drag and Drop Event from In Progress Table.");
        DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
        AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
        Object itemId = t.getItemId();
        Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();


        try {
            Task taskToAdd = taskController.getById(id.intValue());
            String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
            if (t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(doneTable) ){
                inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
                doneTable.removeItem(itemId);
                inProgressTasks.add(taskToAdd);
                doneTasks.remove(taskToAdd);
            }else if(t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(openTable)){
                inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
                openTable.removeItem(itemId);
                inProgressTasks.add(taskToAdd);
                openTasks.remove(taskToAdd);
            }else{
                return;
            }
            logger.info("Sending updates of taskboard to webservice...");
            taskToAdd.setStatus(WorkflowStatusConfigurator.inProgress);
                HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
            MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
        }catch (ClientProtocolException e) {
            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        } catch (IOException e) {
            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        }

    }

    @Override
    public AcceptCriterion getAcceptCriterion() {
        return AcceptAll.get();
    }

}

private class DoneTableHandler implements DropHandler{


    private static final long serialVersionUID = 1L;
    private final Logger logger = LoggerFactory.getLogger(DoneTableHandler.class);

    @Override
    public void drop(DragAndDropEvent event) {
        logger.info("Received Drag and Drop Event from In Done Table.");
        DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
        AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
        Object itemId = t.getItemId();
        Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
        try {
            Task taskToAdd = taskController.getById(id.intValue());
            String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
            if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){
                doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
                inProgressTable.removeItem(itemId);
                doneTasks.add(taskToAdd);
                inProgressTasks.remove(taskToAdd);
            }else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){
                doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
                        taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
                openTable.removeItem(itemId);
                doneTasks.add(taskToAdd);
                openTasks.remove(taskToAdd);
            }else{
                return;
            }
            logger.info("Sending updates of taskboard to webservice...");
            taskToAdd.setStatus(WorkflowStatusConfigurator.done);
            HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
            MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
        }catch (ClientProtocolException e) {
            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        } catch (IOException e) {
            logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
        }

    }

    @Override
    public AcceptCriterion getAcceptCriterion() {
        return AcceptAll.get();
    }

 }

}

有没有人知道或至少知道为什么这不起作用?我按照相同的模式或方式编写了一个代码并且工作正常。唯一的区别是我不使用水平布局。现在,进度和完成表不会对它们上的行进行拖动做出反应。

1 个答案:

答案 0 :(得分:0)

偏离主题:为什么你的观点有@Theme("valo")?据我所知,它与UI类一起使用......

在-话题:

正如我在评论中所说,我不认为这与HorizontalLayout有关。您可能误解了拖动源放置目标概念,或者它只是在代码中滑落。

正如the docs中所描述的那样,拖动从一个源开始,而删除目标上的数据的事件由{{}处理1}}。 如果您查看来源,例如DropHandler,则可以看到

DoneTableHandler

由于您正在聆听if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){ ... }else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){ ... }else{ return; } 上的丢弃,因此它将成为目标,而来源只能是doneTableopenTable,而不是相反。我有一种预感,如果你要在inProgressTable分支中添加一个日志行,你会在每个拖动和放大器上看到它。下降。

下面你可以看到Vaadin 7.7.3中有else和3个表的工作样本,类似于你的。这很快又很脏,所以有改进的余地(欢迎提出建议)但是(例如:position of dropped items),它支持multirow拖动以及来自源表或任何其他的HorizontalLayout过滤器组件比预期组件:

AcceptCriterion

结果:

Vaadin table drag & drop