Wednesday, October 20, 2010

Hover highlighting for drag and drop in a Swing JTree

This was a pain in the butt. I am working on a file browser for iRODS that allows easy movement of data from local file system to iRODS resources. I'm implementing drag-and-drop gestures of all sorts, and the Swing JTree is pretty bare-bones, and lacked hover highlighting when dragging.

I found a very helpful thread here, pertaining to Swing JTables, but I found it easily adaptable to JTree, adding an alpha background color to the original code. In my subclass of JTree, in which I implement DropTargetListener, I added this


class {

private int highlightedRow = -1;
private Rectangle dirtyRegion = null;
private Color highlightColor = new Color(Color.BLUE.getRed(), Color.BLUE.getGreen(), Color.BLUE.getBlue(), 100);


...


@Override
public void dragOver(DropTargetDragEvent dtde) {

Point location = dtde.getLocation();
int closestRow = this.getClosestRowForLocation((int) location.getX(), (int) location.getY());
boolean highlighted = false;

Graphics g = getGraphics();

// row changed

if (highlightedRow != closestRow) {
if (null != dirtyRegion) {
paintImmediately(dirtyRegion);
}

for (int j = 0; j
if (closestRow == j) {

Rectangle firstRowRect = getRowBounds(closestRow);
this.dirtyRegion = firstRowRect;
g.setColor(highlightColor);

g.fillRect((int) dirtyRegion.getX(), (int) dirtyRegion.getY(), (int) dirtyRegion.getWidth(), (int) dirtyRegion.getHeight());
highlightedRow = closestRow;
}
}

}


...

@Override
public void dragExit(DropTargetEvent dte) {
if (null != dirtyRegion) {
paintImmediately(dirtyRegion);
}
}


}

}

No comments: