JTable permits dragging and dropping columns

I was trying to figure out why you couldn’t drag and drop multiple columns in a JTable. It turns out to be a limitation in the JTableHeader interface, which exposes getDraggedColumn, instead of multiple columns.

package javax.swing.plaf.basic;
public class BasicTableHeaderUI extends TableHeaderUI {

    public void paint(Graphics g, JComponent c) {
	if (header.getColumnModel().getColumnCount() <= 0) {
	    return;
	}

       // ...
       TableColumn draggedColumn = header.getDraggedColumn();
        // ...

        // Paint the dragged column if we are dragging.
        if (draggedColumn != null) {
            int draggedColumnIndex = viewIndexForColumn(draggedColumn);
           Rectangle draggedCellRect = header.getHeaderRect(draggedColumnIndex); 

            // Draw a gray well in place of the moving column.
            g.setColor(header.getParent().getBackground());
            g.fillRect(draggedCellRect.x, draggedCellRect.y,
                 draggedCellRect.width, draggedCellRect.height);

            draggedCellRect.x += header.getDraggedDistance();

	    // Fill the background.
	    g.setColor(header.getBackground());
	    g.fillRect(draggedCellRect.x, draggedCellRect.y,
		 draggedCellRect.width, draggedCellRect.height);

            paintCell(g, draggedCellRect, draggedColumnIndex);
        }

	// Remove all components in the rendererPane.
	rendererPane.removeAll();
    }
Bookmark and Share

You should follow me on twitter here

Leave a Reply