Testing Drag 'n Drop in JavaFX UIs (with Demo)
Join the DZone community and get the full member experience.
Join For FreeCurrently, support for dnd is complete. I added the class NodeDragAndDrop which is capable of dragging nodes and dropping them either inside another node or at any point in the UI. To test this class, I used the "Drag and Drop" sample application that comes with NetBeans 6.5. Here is a screenshot of the application:

As you may guessed by now, this sample application allows users to drag the red ball and drop it anywhere in the window.
As a side note, we can assign a unique id to a JavaFX node, to guarantee that node lookup is always reliable. In our example, I assigned the id "ball" to the node to drag and drop:
Stage {
title: "Drag And Drop: v1"
scene: Scene {
content: Group {
content: [
ImageView { image: Image { url: "{__DIR__}images/background.png" } },
DraggableImage {
id: "ball"
maxX: 240
maxY: 320
image: Image { url: "{__DIR__}images/ball.png" }
}
]
}
}
}
We can use the class NodeDragAndDrop directly to simulate a user dragging and dropping a node, but it would require too much code in our tests. Following FEST's approach for compact and readable APIs, I created ImageFixture. This class can handle testing of JavaFX image nodes and also provides shortcut methods for dragging and dropping nodes.
The following test that the red ball can be actually dragged by the user and dropped anywhere in the UI:
@Test public class DragAndDropBallTest {
private JavaFxRobot robot;
private FrameFixture frame;
@BeforeMethod public void setUp() {
robot = BasicJavaFxRobot.robotWithNewAwtHierarchy();
frame = new FrameFixture(robot, launch(Main.class));
}
@AfterMethod public void tearDown() {
robot.cleanUp();
}
public void shouldDragAndDropBall() {
Point target = new Point(100, 100);
ImageFixture image = frame.image("ball");
image.dragAndDropTo(target);
Rectangle2D boundsInScene = image.node().getBoundsInScene();
Point center = centerOf(image.node());
assertThat(boundsInScene.getX()).isEqualTo(target.x - center.x);
assertThat(boundsInScene.getY()).isEqualTo(target.y - center.y);
}
}
The method dragAndDropTo(Point) is the one that simulates a user dragging the ball and dropping it at the point [100, 100] in the window hosting the UI. It uses the AWT Robot to actually move the mouse pointer as if a user was interacting with the UI. Currently, the implementation of dragAndDropTo(Point) drops the node at a point where the center of the node is at the given coordinates. That's why our assertions use the coordinates belonging to the center of the node to verify that the ball was actually dropped at the desired point.
Please click the image to see the test running: (QuickTime format):

Feedback is always appreciated.
Opinions expressed by DZone contributors are their own.
Comments