DragSource 和DropTarget 可以实现控件的拖放,但是当把StyledText作为DragSource 对象时,发现StyledText不能用鼠标选择部分文字,但是可以用shift+方向键或者双击StyledText获取部分选择,请教各位高手是什么原因?能否实现StyledText中的选中文字拖动?

解决方案 »

  1.   

    老兄 转贴一段你看看 或许有用
             final StyledText text1 = new StyledText(shell, style);
    text1.setText(string1);
    DragSource source = new DragSource(text1, DND.DROP_COPY | DND.DROP_MOVE);
    source.setTransfer(new Transfer[] {TextTransfer.getInstance()});
    source.addDragListener(new DragSourceAdapter() {
    Point selection;
    public void dragStart(DragSourceEvent e) {
    selection = text1.getSelection();
    e.doit = selection.x != selection.y;
    }
    public void dragSetData(DragSourceEvent e) {
    e.data = text1.getText(selection.x, selection.y-1);
    }
    public void dragFinished(DragSourceEvent e) {
    if (e.detail == DND.DROP_MOVE) {
    text1.replaceTextRange(selection.x, selection.y - selection.x, "");
    }
    selection = null;
    }
    });

    final StyledText text2 = new StyledText(shell, style);
    text2.setText(string2);
    DropTarget target = new DropTarget(text2, DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
    target.setTransfer(new Transfer[] {TextTransfer.getInstance()});
    target.addDropListener(new DropTargetAdapter() {
    public void dragEnter(DropTargetEvent e) {
    if (e.detail == DND.DROP_DEFAULT)
    e.detail = DND.DROP_COPY;
    }
    public void dragOperationChanged(DropTargetEvent e) {
    if (e.detail == DND.DROP_DEFAULT)
    e.detail = DND.DROP_COPY;
    }
    public void drop(DropTargetEvent e) {
    text2.insert((String)e.data);
    }
    });
      

  2.   

    非常感谢moneybox,我已经测试了这段代码,非常符合要求!我前一段自己也作了一部分就是给styledText加了一个drag的监听,但是在上面加的判断很多而且效果勉强可以,很不稳定!有了你这段代码效果非常好,再次感谢!同时也谢谢lbfhappy的回复,不过整体已经用了SWT,再用swing就不是太好了。