I need to find a word in JTextArea and highlight it, can you help me with this code?

class managerClass implements ActionListener
   {
   
      @Override
      public void actionPerformed(ActionEvent e) {
      
      String myWord = txt.getText();
      Highlighter h = textArea.getHighlighter();
      
         if (e.getSource() == bFind)
         
         {
        	 
        	 
        	   
                pattern = Pattern.compile("\\b"+myWord+"\\b");
                
    

            Matcher matcher = pattern.matcher(myWord);

            while( matcher.find() )
                {
                int start = matcher.start();
                int end = matcher.end();

                try {
					h.addHighlight(start, end, DefaultHighlighter.DefaultPainter);
				} catch (BadLocationException e1) {
					
					e1.printStackTrace();
				}
                }
        	 
        	 
        	 
        	 
            
        	 
        	 JOptionPane.showMessageDialog(null,"No Match Found"); 
        	 
        	 
            }
      
      
      
      
      
      }

I have solved that, but how to set text color now? and why my if else wont work?

public void actionPerformed(ActionEvent e) {
         
            String myWord = txt.getText();
            Highlighter h = textArea.getHighlighter();
         
            if (e.getSource() == bFind)
            
            {
            
            
            
               pattern = Pattern.compile("\\b"+myWord+"\\b");
                
            
            
               Matcher matcher = pattern.matcher(myWord);
					
					boolean matchFound = matcher.matches(); // false
            
            
            
               if (!matchFound){
               
                  while( matcher.find() )
                  {
                     int start = matcher.start();
                     int end = matcher.end();
                  
                     try {
                        Font font = new Font("Verdana", Font.BOLD,40);
                     
                        h.addHighlight(start, end, DefaultHighlighter.DefaultPainter);
                     } 
                        catch (BadLocationException e1) {
                        
                           e1.printStackTrace();
                        }
                  }
               
               }
               
               else
               {
                  JOptionPane.showMessageDialog(null,"No Match Found"); 
               }
            
            
            
            
            
            
            
            
            
            
            }

Edited 4 Years Ago by mehnihma: n/a

you have to define own Highlighter.HighlightPainter or use DefaultHighlighter.DefaultPainter directly, and then to set Highlighter to JTextArea (called textPane here)

textPane.getHighlighter().addHighlight(int start, int end, yourPainter);

I will try that.
But why my if else is not working ? how to do this check?

and how to make yourPainter?
to apply font to it

Edited 4 Years Ago by mehnihma: n/a

I will try that

do you maybe know why is this not working now_ it finds only frist word but nothing else?

class managerClass implements ActionListener
      {
      
         @Override
         public void actionPerformed(ActionEvent e) {
         
            String myWord = txt.getText();
            Highlighter h = textArea.getHighlighter();
            String searchArea = textArea.getText();
         
            if (e.getSource() == bFind)
            
            {
            
            
               String[] searchArray = null;
               searchArray = searchArea.split("[^A-Z][^a-z][^0-9]");
            
               for(String element : searchArray)
               {
                  if(element.equals(myWord))
                  {
                     pattern = Pattern.compile("\\b"+myWord+"\\b");
                  	
                  	
                  	
                     for (int i = 0; i < searchArray.length; i++) 
                     
                     {

                     
                        Matcher matcher = pattern.matcher(searchArray[i]);
                     
                     
                        while( matcher.find() )
                        
                        
                        {
                           int start = matcher.start();
                           int end = matcher.end();
                        
                           try {
                           
                           
                              Highlighter hilit = new DefaultHighlighter();
                           
                           
                              Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
                           
                           //h.addHighlight(start, end, DefaultHighlighter.DefaultPainter);
                              h.addHighlight(start, end, painter);
                           
                           } 
                              catch (BadLocationException e1) {
                              
                                 e1.printStackTrace();
                              }
                        }
                     
                     
                     }
                  
                  
                  
                  
                  }
                  else
                  {
                     JOptionPane.showMessageDialog(null, "No match found", "Message", JOptionPane.INFORMATION_MESSAGE);
                  }
               }
            }

not possible for JTexArea (without using Htlm), you have to use JComponents implementing styled text, maybe

i did it like this

Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
                           
                           
                              h.addHighlight(start, end, painter);
                           	
                              textArea.setSelectionStart(start);
                              textArea.setSelectionEnd(end);
                              textArea.setSelectedTextColor(Color.PINK);

Edited 4 Years Ago by peter_budo: Keep It Clear - Do use code tags when posting any code

It does not work, and I need to change color of the selected text

this isn't simple possible override Caret and by using Highlighter together, there are bunch of code lines and required some knowledges about JTextComponents, I'm out of this thread

I was able to modify/use this example from Swing - A Beginner's Guide in the past to get it working with text area

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CaretDemo {
    JLabel labelAll;
    JLabel labelSelected;
    
    JTextField textField;
    
    JButton buttonCut;
    JButton buttonPaste;
    final String allText = "All text: ";
    final String selectedText = "Selected text: ";
    
    public CaretDemo(){
        JFrame frame = new JFrame("Caret Demo");
        frame.getContentPane().setLayout(new FlowLayout());
        frame.setSize(200, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        labelAll = new JLabel(allText);
        labelSelected = new JLabel(selectedText);
        
        textField = new JTextField("This is a test", 15);
        
        textField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                labelAll.setText((allText + textField.getText()));
                labelSelected.setText(selectedText + textField.getSelectedText());
            }
        });
        
        buttonCut = new JButton("Cut");
        buttonPaste = new JButton("Paste");
        
        buttonCut.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                textField.cut();
                labelAll.setText(allText + textField.getText());
                labelSelected.setText(selectedText + textField.getSelectedText());
            }
        });

        buttonPaste.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                textField.paste();
            }
        });

        textField.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent caretEvent) {
                labelAll.setText(allText + textField.getText());
                labelSelected.setText(selectedText + textField.getSelectedText());
            }
        });

        frame.getContentPane().add(textField);
        frame.getContentPane().add(buttonCut);
        frame.getContentPane().add(buttonPaste);
        frame.getContentPane().add(labelAll);
        frame.getContentPane().add(labelSelected);
        
        textField.setCaretPosition(5);
        textField.moveCaretPosition(7);
        
        frame.setVisible(true);
    }
    
    public  static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CaretDemo();
            }
        });
    }
}
This question has already been answered. Start a new discussion instead.