public void setCaretPosition(int position) { Caret c = textView.getCaret(); // move the caret c.setDot(position); }
@Override public void actionPerformed(ActionEvent e) { JTextComponent textArea = (JTextComponent) e.getSource(); Caret caret = textArea.getCaret(); int dot = caret.getDot(); /* * Move to the beginning/end of selection on a "non-shifted" * left- or right-keypress. We shouldn't have to worry about * navigation filters as, if one is being used, it let us get * to that position before. */ if (!select) { switch (direction) { case SwingConstants.EAST: int mark = caret.getMark(); if (dot != mark) { caret.setDot(Math.max(dot, mark)); return; } break; case SwingConstants.WEST: mark = caret.getMark(); if (dot != mark) { caret.setDot(Math.min(dot, mark)); return; } break; default: } } Position.Bias[] bias = new Position.Bias[1]; Point magicPosition = caret.getMagicCaretPosition(); try { if (magicPosition == null && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) { Rectangle r = textArea.modelToView(dot); magicPosition = new Point(r.x, r.y); } NavigationFilter filter = textArea.getNavigationFilter(); if (filter != null) { dot = filter.getNextVisualPositionFrom( textArea, dot, Position.Bias.Forward, direction, bias); } else { if (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH) { dot = getNSVisualPosition((EditorPane) textArea, dot, direction); } else { dot = textArea .getUI() .getNextVisualPositionFrom( textArea, dot, Position.Bias.Forward, direction, bias); } } if (select) { caret.moveDot(dot); } else { caret.setDot(dot); } if (magicPosition != null && (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH)) { caret.setMagicCaretPosition(magicPosition); } } catch (BadLocationException ble) { Debug.error(me + "Problem while trying to move caret\n%s", ble.getMessage()); } }