选择性拖放

时间:2017-04-12 02:46:59

标签: java drag-and-drop

我有两个JLists和两个JTextfields,我希望能够从一个JList拖动到一个JTextfields,然后另一个JList将拖动到另一个JTextField,但我不希望第一个JList能够拖放第二个文本字段和副verca。那么我将如何做到这一点,我已经搜索了Oracle java教程,但没有找到任何有用的东西?

这是我在JTextfields上使用的TransferHandler类:

class CustomTransferHandler extends TransferHandler {
int action;

public CustomTransferHandler(int action) {
    this.action = action;
    }

    public int getSourceActions(JComponent c) {
        return COPY;
    }

    public Transferable createTransferable(JComponent c) {
        return new StringSelection(((JTextComponent) c).getSelectedText());
    }

    public boolean canImport(TransferHandler.TransferSupport support) {
        // for the demo, we'll only support drops (not clipboard paste)
        if (!support.isDrop()) {
            return false;
        }

        // we only import Strings
        if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            return false;
        }

        boolean actionSupported = (action & support.getSourceDropActions()) == action;
        if (actionSupported) {
            support.setDropAction(action);
            return true;
        }


        return false;
    }

    public boolean importData(TransferSupport ts) {
        try {
            ((JTextComponent) ts.getComponent())
                .setText((String) ts
                         .getTransferable()
                         .getTransferData(DataFlavor.stringFlavor));
            return true;
        } catch(UnsupportedFlavorException | IOException e) {
            return false;
        }
    }
}

0 个答案:

没有答案