JOptionPan 文本的部分突出显示

Partial Highlight of a JOptionPan text

当我用 JOptionPan 吃午饭时,上图就是我得到的。 我只想突出显示“@127.0.0.1”部分,而不是“root”部分。 这是我正在使用的代码:

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

有办法吗?

使用 JTextArea 附带的 DefaultHighlighter。例如,

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));          
   }
}

我建议使用 JOptionPane.showConfirmDialog(...) 而不是 JOptionPane.showInputDialog(...):

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public final class PartialHighlightTest {
  public static void main(String... args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    String msg = "<html>Veuillez: <font color=green>root<font color=red>@adresse";
    String loginHistory = "root@127.0.0.1";
    //JOptionPane.showInputDialog(
    //  null, msg, "title", JOptionPane.PLAIN_MESSAGE, null, null, loginHistory);

    Box box = Box.createVerticalBox();
    box.add(new JLabel(msg));
    JTextField textField = new JTextField();
    textField.addAncestorListener(new AncestorListener() {
      @Override public void ancestorAdded(AncestorEvent e) {
        JTextField field = (JTextField) e.getComponent();
        field.requestFocusInWindow();
        String t = field.getText();
        field.select(t.indexOf("@"), t.length());
      }
      @Override public void ancestorMoved(AncestorEvent e) {}
      @Override public void ancestorRemoved(AncestorEvent e) {}
    });
    box.add(textField);
    textField.setText(loginHistory);
    JOptionPane.showConfirmDialog(
      null, box, "title",
      JOptionPane.OK_CANCEL_OPTION,
      JOptionPane.PLAIN_MESSAGE);
    System.out.println(textField.getText());
  }
}