简体   繁体   English

JLabel transferhandler 复制工作但不移动

[英]JLabel transferhandler copy working but not move

I want to move text from one jlabel onto another, but for some reason, only copy is working and not move.我想将文本从一个 jlabel 移到另一个 jlabel 上,但由于某种原因,只有副本在工作而不是移动。 I am using a transferhandler so in handler.exportAsDrag(comp, e, TransferHandler.MOVE);我在 handler.exportAsDrag(comp, e, TransferHandler.MOVE) 中使用了 transferhandler; only TransferHandler.COPY works.只有 TransferHandler.COPY 有效。

            add1 = new JLabel("", JLabel.CENTER);
        add1.setTransferHandler(new TransferHandler("text"));
        add1.setBorder(b2);


        add2 = new JLabel("", JLabel.CENTER);
        add2.setTransferHandler(new TransferHandler("text"));
        add2.setBorder(b2);

            MouseListener listener = new DragMouseAdapter();

        add1.addMouseListener(listener);
        add2.addMouseListener(listener);

            panel2a.add(add1);

        panel2a.add(add2);

They are dragged using this private inner class使用这个私有内部类拖动它们

private class DragMouseAdapter extends MouseAdapter
    {
        public void mousePressed(MouseEvent e)
        {
            JComponent comp = (JComponent)e.getSource();
            TransferHandler handler = comp.getTransferHandler();

            //c.setOpaque(true);
            handler.exportAsDrag(comp, e, TransferHandler.MOVE);

        }


    }

The implementation of TransferHandler.getSourceActions() by default returns COPY if the specified property exists and has a proper getter: TransferHandler.getSourceActions()的实现默认返回COPY如果指定的属性存在并且有一个合适的 getter:

public int getSourceActions(JComponent c) {
PropertyDescriptor prop = getPropertyDescriptor(c);
if (prop != null) {
    return COPY;
}
return NONE;
}

As a result, when you specify MOVE in exportAsDrag() the handler decides the action is not supported.因此,当您在exportAsDrag()指定MOVE ,处理程序决定不支持该操作。

You can override this method to add whatever actions your source supports.您可以覆盖此方法以添加您的源支持的任何操作。 For example:例如:

add1.setTransferHandler(new TransferHandler("text") {
    @Override
    public int getSourceActions(JComponent c) {
        return COPY | MOVE;
    }
});

EDIT: implement exportDone编辑:实施 exportDone

this.setTransferHandler(new TransferHandler("text") {
    @Override
    protected void exportDone(JComponent source, Transferable data, int action) {
        if (action == MOVE){
            ((JLabel) source).setText("");
        }
    }

    @Override
    public int getSourceActions(JComponent c) {
        return COPY | MOVE;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM