How to paint the Dropline of a RowHeader-JTable on the Main-JTable during a DragAndDrop?

后端 未结 4 1461
盖世英雄少女心
盖世英雄少女心 2021-02-07 15:16

I\'m using a second JTable in the Viewport of a JScrollPane to build a RowHeader for a main table. DragAndDrop on the main table is disabled. On the rowheader table DnD is enabl

4条回答
  •  执念已碎
    2021-02-07 15:40

    I suggest you to do like this (using Swing's drag & drop functionality):

        RowHeaderTable rowTable = new RowHeaderTable(mainTable);
        rowTable.setAutoscrolls(true);
        rowTable.setDragEnabled(true);
        rowTable.setTransferHandler(new RowHeaderTransferHandler(mainTable));
        rowTable.setDropMode(DropMode.INSERT_ROWS);
        try {
            DropTarget dropTarget = rowTable.getDropTarget();
            dropTarget.addDropTargetListener(rowTable);
        }
        catch(TooManyListenersException e) {
            e.printStackTrace();
        }
    

    Now you have to implement DropTargetListener:

    public class RowHeaderTable extends JTable implements ChangeListener, PropertyChangeListener, DropTargetListener {
    

    These are 2 methods that you should be interested in:

        @Override
        public void dragEnter(DropTargetDragEvent dtde) { shouldPaint = true }
    
        @Override
        public void dragExit(DropTargetEvent dte) { shouldPaint = false }
    

    Now you should manipulate your mainTable (to paint this "green line") using your TranserHandler:

        @Override
        public boolean canImport(TransferSupport supp) {
            DropLocation location = supp.getDropLocation();
            if(location instanceof javax.swing.JTable.DropLocation && shouldPaint) {
                javax.swing.JTable.DropLocation tableLocation = (javax.swing.JTable.DropLocation) location;
                int rowToInsert = tableLocation.getRow();
                //paint somehow the "green line"
                //remember that canImport is invoked when you move your mouse
            }
            return true;
        }
    

    Basically you should implement your own row renderer or something similar (like in @naugler answer). You should somehow provide boolean shouldPaint to your TransferHandler as well. But this is not a big deal to implement.

    Hope this helps.

提交回复
热议问题