Java Swing How to - Highlight current row in JTextPane








Question

We would like to know how to highlight current row in JTextPane.

Answer

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
//ww w  . j  ava  2  s . com
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new HighlightLineTextPane());
    frame.setBounds(100, 100, 300, 400);
    frame.setVisible(true);
  }
}

class HighlightLineTextPane extends JTextPane {
  public HighlightLineTextPane() {
    setOpaque(false);
  }
  @Override
  protected void paintComponent(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    try {
      Rectangle rect = modelToView(getCaretPosition());
      if (rect != null) {
        g.setColor(Color.RED);
        g.fillRect(0, rect.y, getWidth(), rect.height);
      }
    } catch (BadLocationException e) {
      System.out.println(e);
    }
    super.paintComponent(g);
  }

  @Override
  public void repaint(long tm, int x, int y, int width, int height) {
    super.repaint(tm, 0, 0, getWidth(), getHeight());
  }
}