We can perform Drag and Drop actions in WebDriver using Actions class. Below is the code for this:
Actions builder = new Actions(driver);
builder.dragAndDrop(source, target);
Here 'source' is the source(from element) web element and 'target' is the target(to element) web element.
Or
/**
* Drags the web element <code>fromWebElement</code> and drop at web element
* <code>toWebElement</code>
* @param fromWebElement
* @param toWebElement
*/
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement).release(toWebElement).build();
dragAndDrop.perform();
}
Using robot:
/**
* Drags the web element <code>fromWebElement</code> and drop at web element
* <code>toWebElement</code>
* @param fromWebElement
* @param toWebElement
*/
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
Point coordinates1 = fromWebElement.getLocation();
Point coordinates2 = toWebElement.getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates1.getX(), coordinates1.getY());
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseMove(coordinates2.getX(), coordinates2.getY());
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
Actions builder = new Actions(driver);
builder.dragAndDrop(source, target);
Here 'source' is the source(from element) web element and 'target' is the target(to element) web element.
Or
/**
* Drags the web element <code>fromWebElement</code> and drop at web element
* <code>toWebElement</code>
* @param fromWebElement
* @param toWebElement
*/
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement).release(toWebElement).build();
dragAndDrop.perform();
}
Using robot:
/**
* Drags the web element <code>fromWebElement</code> and drop at web element
* <code>toWebElement</code>
* @param fromWebElement
* @param toWebElement
*/
public void dragAndDrop(WebElement fromWebElement, WebElement toWebElement) {
Point coordinates1 = fromWebElement.getLocation();
Point coordinates2 = toWebElement.getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates1.getX(), coordinates1.getY());
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseMove(coordinates2.getX(), coordinates2.getY());
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
No comments:
Post a Comment