JTextArea - Highlight Text While Scrolling Up or Down
Posted
by
Sujay
on Stack Overflow
See other posts from Stack Overflow
or by Sujay
Published on 2012-06-08T16:34:04Z
Indexed on
2012/06/08
16:40 UTC
Read the original article
Hit count: 283
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));
textArea.setEditable(false);
final Action selectLine = getAction(textArea, DefaultEditorKit.selectLineAction);
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {
selectLine.actionPerformed(null);
}
});
textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);
}
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];
break;
}
}
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:
Line1
Line2
Line3
Line4
Line5
(i.e. there might be new lines between two particular lines of data)
© Stack Overflow or respective owner