Sujay Sujay -4 years ago 47
Java Question

JTextArea - Highlight Text While Scrolling Up or Down

I'm trying to work with a non-editable JTextArea added to a JScrollPane. I want a line to be highlighted when the user clicks on that specific line. I could implement this part using the following code:

public static void initHighlightOption(final JTextArea textArea){

textArea.setFont(new Font("Courier New", Font.PLAIN, 12));

final Action selectLine = getAction(textArea, DefaultEditorKit.selectLineAction);

textArea.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {


public static Action getAction(JTextArea textArea, String name) {
Action action = null;
Action[] actions = textArea.getActions();

for (int i = 0; i < actions.length; i++) {
if (name.equals(actions[i].getValue(Action.NAME).toString())) {
action = actions[i];

return action;

What I want to add is that once a line is highlighted and user scrolls up/down using keyboard up/down key, i want the current line to be highlighted. Is this possible by adding a keyListener? I'm stuck on how highlight data while scrolling up.

The text area contains data like this:




(i.e. there might be new lines between two particular lines of data)

Answer Source

What your asking for is not so easy to do. First off use a JTextPane instead of a JTextArea, it'll be much easier to handle. You will be need to get the Highlighter object from it

Highlighter hl = textPane.getHighlighter();

and you would probably have to keep track of your caret position each time the user scrolls with the arrow keys. When doing that you need to programatically change the highlights; something like:

Highlighter.Highlight myHighlight = null;
Highlighter.Highlight[] highlights = textPane.getHighlighter().getHighlights();
myHighlight = highlights[0]; //assuming there is one only

try {
      hl.changeHighlight(myHighlight, myHighlight.getStartOffset()+1, myHighlight.getEndOffset());
catch(BadLocationException e) {

You can probably put this in your onKeyReleased() method. You kind of get the idea of what you're going to have to do. Read up on using JTextPane and Highlighter classes in the Java API docs, it will really help you alot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download