Reputation: 6783
I have a JTextArea
which consists of lines (some of them possibly duplicates of one another). I've a requirement where I've to highlight the selected line upon right-click. The code that I'm using to highlight is as follows:
String highlightedText = textArea.getSelectedText();
if(highlightedText != null)
{
try{
int index = textArea.getText().indexOf(highlightedText, textArea.getCaretPosition());
textArea.getHighlighter().addHighlight(index - 1, index + highlightedText.length(),
new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
}catch (BadLocationException ex) {
}
}
While the highlight upon right-click works, the problem is I cannot get the index of the selected line in the presence of duplicates. So if there're lines like
AAAA
BBBB
AAAA
CCCC
DDDD
AAAA
I cannot get the index of the second "AAAA" when the user tries to highlight this particular line. Can someone help me out with an idea/suggestion to work this this? Thanks!
Upvotes: 2
Views: 948
Reputation: 7943
You had it almost all by yourself there were few issues though.
getSelectionStart()
rather than getCaretPosition()
.index
not from index-1
.Please see the example below. Select what you want to highlight right click on the textArea or press the button to highlight your selection:
public class HighlightingTextArea {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JTextArea textArea = new JTextArea(10, 44);
textArea.append("AAAA\nBBBB\nAAAA\nCCCC\nDDDD\nAAAA");
JButton b = new JButton(new AbstractAction("highlight") {
@Override
public void actionPerformed(ActionEvent e) {
highlightTextAreaSelection(textArea);
}
});
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if (e.getButton() == MouseEvent.BUTTON3) {
highlightTextAreaSelection(textArea);
}
}
});
JPanel panel = new JPanel(new BorderLayout());
panel.add(textArea);
panel.add(b, BorderLayout.SOUTH);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setVisible(true);
}
});
}
private static void highlightTextAreaSelection(JTextArea textArea) {
String highlightedText = textArea.getSelectedText();
if (highlightedText != null) {
try {
int index = textArea.getText().indexOf(highlightedText, textArea.getSelectionStart());
textArea.getHighlighter().addHighlight(index, index + highlightedText.length(),
new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
} catch (BadLocationException ex) {
}
}
}
}
Upvotes: 2