Reputation: 80
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 ?
Upvotes: 1
Views: 177
Reputation: 9833
I'd suggest using a JOptionPane.showConfirmDialog(...)
instead of a 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 = "[email protected]";
//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());
}
}
Upvotes: 2
Reputation: 7199
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));
}
}
Upvotes: 1