Monday, 18 February 2013

Dragging and dropping shapes in Java

Here's my basic drag and drop implementation in a little over 100 lines of code. What you'll need (to do):

First, the list of shapes. Here's a very simple class that acts as a square. All it has are its x and y coordinates, getters & setters for them and then a method that draws the shape.

Square

Now let's think about how the drag and drop works. What do you actually do? Whell, you press your mouse button to select your shape. Then you drag the shape where you want it to be. Then you release the mouse button when you are done dragging to deselect the shape. That's exactly the role our above overriden methods will have: select - move - deselect.

We'll keep a field, selected (of type Square) that knows which shape is selected - if any. mouseReleased will always set it to null. This is the easiest method.

mousePressed isn't much harder though - here we want to know which shape was selected. To do that, we save the coordinates where the button was pressed and check whether any of the shapes in our list resides at those coordinates. If yes, assign our selected field the value of the respective shape. If none of the shapes is in that area, the selected will stay null.

Finally, mouseDragged. If no shape was selected, then it's easy: just return. If we did select a shape, then we need to update its coordinates. As we drag the mouse on the screen, the shape beneath it needs to, well, stay beneath it. For this we are going to take our pointer's coordinates and assign them to our shape. In Java, squares (rectangles) are drawn from the top left corner, so I adjusted my new coordinates for the shape so that its center will always be where the mouse is pointing. Then, of course, we repaint.

Here's the full code:
MyPanel

Finally, put the panel in an applet or frame and there you go.

No comments:

Post a Comment