• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextAreaに行ハイライトカーソルを表示
#navi(../)
*JTextAreaに行ハイライトカーソルを表示 [#b84f9cac]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-07-24~
更新日:&lastmod;

#contents

**概要 [#x8bd671d]
JTextAreaのカーソルがある行をハイライト表示します。

#screenshot

**サンプルコード [#vabb7f2d]
#code{{
class HighlightCursorTextArea extends JTextArea {
  private static final Color linecolor = new Color(250,250,220);
  private final DefaultCaret caret;
  public HighlightCursorTextArea() {
    super();
    setOpaque(false);
    Caret caret = new DefaultCaret() {
    caret = new DefaultCaret() {
      protected synchronized void damage(Rectangle r) {
        if(r!=null) {
          JTextComponent c = getComponent();
          x = 0; y = r.y;
          x = 0;
          y = r.y;
          width  = c.getSize().width;
          height = r.height;
          repaint();
          c.repaint();
        }
      }
    };
    caret.setBlinkRate(getCaret().getBlinkRate());
    setCaret(caret);
  }
  private final Color linecolor = new Color(250,250,220);
    protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      Insets i = getInsets();
      int h = g2.getFontMetrics().getHeight();
      int y = (getLineAtCaret(this)-1)*h+i.top;
      g2.setPaint(linecolor);
      g2.fillRect(i.left, y, getSize().width-i.left-i.right, h);
      super.paintComponent(g);
    }
    public static int getLineAtCaret(JTextComponent component) {
    int caretPosition = component.getCaretPosition();
    Element root = component.getDocument().getDefaultRootElement();
    return root.getElementIndex(caretPosition)+1;
  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);
  }
}
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#jb96e960]
ほぼ、[[JTextAreaに行カーソルを表示>Swing/LineCursor]]とやっていることは同じです。

違うのは、以下の三点になります。
違うのは、以下の点になります。
-ViewPortの色をscroll.getViewport().setBackground(Color.WHITE)にする
-JTextAreaをsetOpaque(false)と透明にする
-JTextAreaのpaintComponent(Graphics g)をオーバーライドするとき、カーソルのある行を塗りつぶしてからsuper.paintComponent(g)する

//**参考リンク
**参考リンク [#y021b082]
-[[JTextAreaに行カーソルを表示>Swing/LineCursor]]

**コメント [#v72b7b28]
- 行の折り返しに対応しました。 -- [[terai]] &new{2008-03-17 (月) 16:22:56};

#comment