How to Add Selection Listener to JTextArea

Here is a helpful article on how to listen text selection changes in JTextArea, (ofcourse on any sub class of JTextComponent). With the beautiful swing package, we've got a new listener called the CaretListener, which will listen caret update events. There are two important terms you need to know called the dot and the mark.

dot represents the current caret position.
mark represents the selection end other than the dot.
Note that dot can be greater than mark or mark can be greater the dot.


import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class TextSelectionListener extends JFrame
{
private JTextArea jt;
private JScrollPane js;
public TextSelectionListener()
{
createAndShowGUI();
}

private void createAndShowGUI()
{
setTitle("Listening to Selection Changes in JTextArea");
setSize(400,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

jt=new JTextArea(20,25);
js=new JScrollPane(jt);
add(js);

jt.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent ce)
{
int dot=ce.getDot();
int mark=ce.getMark();
if(dot!=mark)
{
setTitle("Text selected is "+jt.getSelectedText()+" [dot: "+dot+",mark: "+mark+"]");
}
else setTitle("Text not selected");
}
});

}

public static void main(String args[])
{
new TextSelectionListener();
}
}

Output of the program

Listening to Text Selection Changes in JTextArea

Explaining the TextSelectionListener

Well there is nothing in fact to say about this. But i would like to point out that, a CaretEvent is generated whenever the caret updates it's position. Some may be in a thought that the dot is the selection start and mark is the selection end. This is not always true, it is only true when the selection is made from right to left. To get the selection start and end, use getSelectionStart() and getSelectionEnd() methods.

Note: dot==mark when the text is not selected.

Also see my post on setting background image in JTextArea

Image Credit: https://duke.dev.java.net/


Posted by at on

Tags: Swing Event Handling, Swing Hacks,