1

Есть окно, в нём JEditorPane. По умолчанию caret - вертикальная палочка, если можно так сказать. А мне нужно чтобы она была снизу и горизонтальная (как в консоли Windows). Можно это как-то реализовать?

1 ответ 1

1

Вам нужно будет написать свою каретку.

Пример взят отсюда:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.JTextComponent;

public class Test1 extends DefaultCaret {

  public Test1() {
    setBlinkRate(500); // half a second
  }

  @Override
  protected synchronized void damage(Rectangle r) {
    if (r == null)
      return;
    x = r.x;
    y = r.y + (r.height * 4 / 5 - 3);
    width = 5;
    height = 5;
    repaint(); // calls getComponent().repaint(x, y, width, height)
  }

  @Override
  public void paint(Graphics g) {
    JTextComponent comp = getComponent();
    if (comp == null)
      return;

    int dot = getDot();
    Rectangle r = null;
    try {
      r = comp.modelToView(dot);
    } catch (BadLocationException e) {
      return;
    }
    if (r == null)
      return;

    int dist = r.height * 4 / 5 - 3; // will be distance from r.y to top

    if ((x != r.x) || (y != r.y + dist)) {
      repaint(); // erase previous location of caret
      x = r.x; // set new values for x,y,width,height
      y = r.y + dist;
      width = 5;
      height = 5;
    }

    if (isVisible()) {
      g.setColor(comp.getCaretColor());
      g.drawLine(r.x, r.y + dist + 4, r.x + 4, r.y + dist + 4);
    }
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame("CornerCaret demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextArea area = new JTextArea(8, 32);
    area.setCaret(new Test1());
    area
        .setText("This is the story\nof the hare who\nlost his spectacles.");
    frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}
1
  • Спасибо! Всё идеально работает!)
    – tovarish
    30 мая 2017 в 10:02

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.