• title: JTextAreaに行ハイライトカーソルを表示 tags: [JTextArea, Caret, JViewport] author: aterai pubdate: 2006-07-24 description: JTextAreaのカーソルがある行をハイライト表示します。

概要

JTextAreaのカーソルがある行をハイライト表示します。

サンプルコード

class HighlightCursorTextArea extends JTextArea {
  private static final Color linecolor = new Color(250,250,220);
  private final DefaultCaret caret;
  public HighlightCursorTextArea() {
    super();
    setOpaque(false);
    caret = new DefaultCaret() {
      @Override protected synchronized void damage(Rectangle r) {
        if(r!=null) {
          JTextComponent c = getComponent();
          x = 0;
          y = r.y;
          width  = c.getSize().width;
          height = r.height;
          c.repaint();
        }
      }
    };
    caret.setBlinkRate(getCaret().getBlinkRate());
    setCaret(caret);
  }
  @Override protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Insets i = getInsets();
    int h = caret.height;
    int y = caret.y;
    g2.setPaint(linecolor);
    g2.fillRect(i.left, y, getSize().width-i.left-i.right, h);
    super.paintComponent(g);
  }
}
View in GitHub: Java, Kotlin

解説

ほぼ、JTextAreaに行カーソルを表示とやっていることは同じです。

違うのは、以下の点になります。

  • Viewportの色をscroll.getViewport().setBackground(Color.WHITE)にする
  • JTextArea#setOpaque(false)と設定して透明にする
  • JTextArea#paintComponent(...)をオーバーライドするとき、カーソルのある行を塗りつぶしてからsuper.paintComponent(g)する

Swing - Stretching background colour across whole JTextPane for one line of text の Darryl.Burke さんのコード(以下に部分コピー)のように、BasicTextPaneUI#paintBackgroundをオーバーライドする方法(こちらの方がシンプルで美しいかも)もあります。

//JTextPane textPane = new JTextPane();
//textPane.setUI(new LineHighlightTextPaneUI(textPane));
class LineHighlightTextPaneUI extends BasicTextPaneUI {
  private final JTextPane tc;
  public LineHighlightTextPaneUI(JTextPane t) {
    tc = t;
    tc.addCaretListener(new CaretListener() {
      @Override public void caretUpdate(CaretEvent e) {
        tc.repaint();
      }
    });
  }
  @Override public void paintBackground(Graphics g) {
    super.paintBackground(g);
    try{
      Rectangle rect = modelToView(tc, tc.getCaretPosition());
      int y = rect.y;
      int h = rect.height;
      g.setColor(Color.YELLOW);
      g.fillRect(0, y, tc.getWidth(), h);
    }catch(BadLocationException ex) {
      ex.printStackTrace();
    }
  }
}

これらの方法なら、JTextEditorJTextPaneで行の高さが異なる場合でも、うまくハイライトできるようです。

LineHighlighter1.png

参考リンク

コメント