Search code examples
javaswinghighlightjoptionpane

Partial Highlight of a JOptionPan text


enter image description here

When I lunch my JOptionPan, the above image is what I get. I'd like to have only the part "@127.0.0.1" highlighted, without the "root" part. This is the code I'm using:

            JOptionPane.showInputDialog(null, msg
                ,"Connection à l'"+this.nom, JOptionPane.PLAIN_MESSAGE, null, null, loginHistory);

Is there a way to do it ?


Solution

  • Use the DefaultHighlighter that comes with your JTextArea. For e.g.,

    import java.awt.Color;
    import javax.swing.*;
    
    public class Test {
       public static void main(String[] args) {
    
          JTextArea textArea = new JTextArea(10, 30);
    
          textArea.setText("This is a text");
    
          Highlighter highlighter = textArea.getHighlighter();
          HighlightPainter painter = 
                 new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
          int p0 = text.indexOf("is");
          int p1 = p0 + "is".length();
          highlighter.addHighlight(p0, p1, painter );
    
          JOptionPane.showMessageDialog(null, new JScrollPane(textArea));          
       }
    }