MarqueSelectionListener extends MouseInputAdapter { @Override public void mouseDragged(MouseEvent e) { if (selection == null) { if (!dragStart) { Container c = (Container) e.getSource(); if (!isInOverridingAction(c) && selectionProvider.pointInTopLevelPanel(e.getLocationOnScreen())) { selection = createSelection(); clickX = e.getX(); clickY = e.getY(); selection.setBounds(clickX, clickY, 1, 1); rootPanel.add(selection); rootPanel.setComponentZOrder(selection, 0); } } } else { int mouseX = e.getX(); int mouseY = e.getY(); if (mouseX >= clickX) { if (mouseY >= clickY) { selection.setBounds(clickX, clickY, mouseX - clickX, mouseY - clickY); } else { int width = mouseX - clickX; selection.setBounds(mouseX - width, mouseY, width, clickY - mouseY); } } else { if (mouseY >= clickY) { selection.setBounds(mouseX, clickY, clickX - mouseX, mouseY - clickY); } else { selection.setBounds(mouseX, mouseY, clickX - mouseX, clickY - mouseY); } } } dragStart = true; } MarqueSelectionListener(JComponent panel, MultipleSelectionProvider provider); @Override void mouseDragged(MouseEvent e); @Override void mouseReleased(MouseEvent e);  }
@Test(dataProvider="mouseDataWithCursor") public void testMouseDraggedStartCursorMove(MouseEvent e) { Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(true); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 0, "marquee selection should not be added because cursor indicates move or resize event" ); }
@Test public void testMouseDraggedInsideAComponent() { JPanel panel = new JPanel(); panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); MouseEvent e = new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false); Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(false); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 0, "marquee selection should not be added the starting mouse event is inside an enclosing panel" ); }
@Test(dataProvider="mouseDraggingDirections") public void testMouseDraggedStart(Rectangle expectedBounds, Point mouseClicked) { JPanel panel = new JPanel(); panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); MouseEvent e = new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false); Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(true); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 1, "marquee selection should have been started" ); e = new MouseEvent(panel,1234,System.currentTimeMillis(),0,mouseClicked.x,mouseClicked.y,1,false); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents()[0].getBounds(),expectedBounds); }