Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You had it almost all by yourself there were few issues though.</p> <ol> <li>You should use <code>getSelectionStart()</code> rather than <code>getCaretPosition()</code>.</li> <li>Highlight should start from <code>index</code> not from <code>index-1</code>.</li> </ol> <p><strong>Please see the example below.</strong> Select what you want to highlight right click on the textArea or press the button to highlight your selection:</p> <pre><code>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) { } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload