JEdi​​torPane矩形(列)选择模式

时间:2011-04-10 22:05:15

标签: java swing selection jeditorpane

我想知道如何扩展JEditorPane(或任何其他swing文本编辑组件)来处理矩形(列)选择模式。它是当前文本编辑器中众所周知的功能,您可以从偏移(列)开始选择多个行(行),以偏移(列)结束,看起来像选择文本的矩形,然后您键入的内容将覆盖同时选择每一行(行)。

一个想法是覆盖选择并通过跟踪鼠标事件突出显示矩形形式的每一行来创建假选择,并跟踪这些信息以在键入时使用它。但是,我不确定如何覆盖选择并跟踪鼠标,也不确定如何重定向键入以影响每一行。

任何形式的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

找到this little code snippet,其中涉及自定义Caret(处理碎片选择)和Highlighter(以显示片段):

class MyCaret extends DefaultCaret {

Point lastPoint=new Point(0,0);
public void mouseMoved(MouseEvent e) {
    super.mouseMoved(e);
    lastPoint=new Point(e.getX(),e.getY());
}
public void mouseClicked(MouseEvent e) {
    super.mouseClicked(e);
    getComponent().getHighlighter().removeAllHighlights();
}

protected void moveCaret(MouseEvent e) {
    Point pt = new Point(e.getX(), e.getY());
    Position.Bias[] biasRet = new Position.Bias[1];
    int pos = getComponent().getUI().viewToModel(getComponent(), pt, biasRet);
    if(biasRet[0] == null)
        biasRet[0] = Position.Bias.Forward;
    if (pos >= 0) {
        setDot(pos);
        Point start=new Point(Math.min(lastPoint.x,pt.x),Math.min(lastPoint.y,pt.y));
        Point end=new Point(Math.max(lastPoint.x,pt.x),Math.max(lastPoint.y,pt.y));
        customHighlight(start,end);
    }
}

protected void customHighlight(Point start, Point end) {
    getComponent().getHighlighter().removeAllHighlights();
    int y=start.y;
    int firstX=start.x;
    int lastX=end.x;

    int pos1 = getComponent().getUI().viewToModel(getComponent(), new Point(firstX,y));
    int pos2 = getComponent().getUI().viewToModel(getComponent(), new Point(lastX,y));
    try {
        getComponent().getHighlighter().addHighlight(pos1,pos2,
                 ((DefaultHighlighter)getComponent().getHighlighter()).DefaultPainter);
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    y++;
    while (y<end.y) {
        int pos1new = getComponent().getUI().viewToModel(getComponent(), new Point(firstX,y));
        int pos2new = getComponent().getUI().viewToModel(getComponent(), new Point(lastX,y));
        if (pos1!=pos1new)  {
            pos1=pos1new;
            pos2=pos2new;
            try {
                getComponent().getHighlighter().addHighlight(pos1,pos2,
                         ((DefaultHighlighter)getComponent().getHighlighter()).DefaultPainter);
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        y++;
    }
}
}

无论如何,我从未运行过该代码(it's Stanislav's)。