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.

Highlight of discontinous string in JTextArea in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer