Swing/LineHighlighter のバックアップ(No.3)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/LineHighlighter へ行く。
  
- 1 (2007-04-10 (火) 16:27:02)
 - 2 (2007-08-02 (木) 11:14:23)
 - 3 (2008-03-17 (月) 16:22:35)
 - 4 (2008-03-17 (月) 17:23:03)
 - 5 (2008-03-17 (月) 18:51:09)
 - 6 (2012-10-19 (金) 20:14:31)
 - 7 (2013-02-27 (水) 13:49:26)
 - 8 (2013-03-15 (金) 16:56:20)
 - 9 (2013-08-30 (金) 01:37:31)
 - 10 (2013-10-23 (水) 20:27:47)
 - 11 (2014-11-22 (土) 03:59:58)
 - 12 (2014-11-25 (火) 03:03:31)
 - 13 (2014-12-30 (火) 15:42:38)
 - 14 (2016-04-13 (水) 17:45:02)
 - 15 (2016-09-18 (日) 21:06:37)
 - 16 (2017-11-01 (水) 15:18:58)
 - 17 (2019-05-22 (水) 17:25:00)
 - 18 (2021-02-14 (日) 22:46:58)
 - 19 (2024-01-24 (水) 23:47:38)
 - 20 (2025-01-03 (金) 08:57:02)
 - 21 (2025-01-03 (金) 09:01:23)
 - 22 (2025-01-03 (金) 09:02:38)
 - 23 (2025-01-03 (金) 09:03:21)
 - 24 (2025-01-03 (金) 09:04:02)
 - 25 (2025-06-19 (木) 12:41:37)
 - 26 (2025-06-19 (木) 12:43:47)
 
 
TITLE:JTextAreaに行ハイライトカーソルを表示
JTextAreaに行ハイライトカーソルを表示
編集者:Terai Atsuhiro
作成日:2006-07-24
更新日:2024-01-24 (水) 23:47:38
概要
JTextAreaのカーソルがある行をハイライト表示します。
#screenshot
サンプルコード
class HighlightCursorTextArea extends JTextArea {
  public HighlightCursorTextArea() {
    super();
    setOpaque(false);
    Caret caret = new DefaultCaret() {
      protected synchronized void damage(Rectangle r) {
        if(r!=null) {
          JTextComponent c = getComponent();
          x = 0; y = r.y;
          width  = c.getSize().width;
          height = r.height;
          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;
  }
}
- &jnlp;
 - &jar;
 - &zip;
 
解説
ほぼ、JTextAreaに行カーソルを表示とやっていることは同じです。
違うのは、以下の三点になります。
- ViewPortの色をscroll.getViewport().setBackground(Color.WHITE)にする
 - JTextAreaをsetOpaque(false)と透明にする
 - JTextAreaのpaintComponent(Graphics g)をオーバーライドするとき、カーソルのある行を塗りつぶしてからsuper.paintComponent(g)する