Highlight of discontinous string in JTextArea in Java
Description
The following code shows how to highlight of discontinous string in JTextArea.
Example
import java.awt.Font;
//from ww w . ja v a 2s . c o m
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Main extends JFrame {
public Main() {
JTextArea textarea = new JTextArea("Initial Text");
textarea.setFont(new Font("LucidaSans", Font.PLAIN, 40));
add(textarea);
String charsToHighlight = "aeiouAEIOU";
Highlighter h = textarea.getHighlighter();
h.removeAllHighlights();
String text = textarea.getText().toUpperCase();
for (int i = 0; i < text.length(); i += 1) {
char ch = text.charAt(i);
if (charsToHighlight.indexOf(ch) >= 0)
try {
h.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
} catch (Exception ble) {
}
}
}
public static void main(String[] args) {
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »