highlighning a pattern in TextArea, please help
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: highlighning a pattern in TextArea, please help

  1. #1
    Join Date
    Nov 2013
    Posts
    4

    Exclamation highlighning a pattern in TextArea, please help

    I am doing a very quick program and Basically it is a word finder.
    Or a pattern finder using Regular Expressions using both the pattern class and matcher class.
    By clicking a "refresh" button the pattern entered by the user in a JTextField will be compile with the current text in the JTextArea.
    Using my matcher I will find all indexes of every match there is in the text and highlighted (any color), but it would be cool if I could highlight all matches with random colors. At least get the highlighter to work.
    So the problem is the text is not appearing to be highlighted (patterns). I don't even know If I am highlighting all patterns found in my JTextArea.
    Please help urgently.

    Here is the code I implemented quickly after the user pushes the "refresh button" (which takes you to this method):

    NOTE: "area" is my JTextArea where I have the user's current text, where the patterns are supposed to be.

    method call:
    //if refresh button is pushed
    textArea.setText(refreshBox(textArea));


    method:
    public static String refreshBox(JTextArea area) throws BadLocationException {
    // TODO Auto-generated method stub

    matcherR = pattern.matcher(area.getText()); //to find pattern



    redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);

    while(matcherR.find()){
    String str = matcherR.group().toString(); //the matcher found

    try {
    area.getHighlighter().addHighlight(area.getText().indexOf(str), str.length(), redPainter);

    } catch (BadLocationException ex) { ex.printStackTrace(); }


    }
    return area.getText();
    }

  2. #2
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,448

    Re: highlighning a pattern in TextArea, please help

    Can you make a small complete program that compiles and excutes for testing?
    Please wrap the code in code tags:
    [code]
    THE CODE HERE
    [/code]
    Norm

  3. #3
    Join Date
    Nov 2013
    Posts
    4

    Unhappy Re: highlighning a pattern in TextArea, please help

    Quote Originally Posted by Norm View Post
    Can you make a small complete program that compiles and excutes for testing?
    Please wrap the code in code tags:
    [code]
    THE CODE HERE
    [/code]
    Sure, Please try to ignore the syntax, I just made this, so its not that well automated code.
    Anyway It will execute a frame, then in this you will find a jtextfield, where you need to put a pattern, or word. And in the bottom, u find the jtextarea, which you need to put inside a string, sentence, whatever. then by hitting "Refresh" button the program will put all matches found in UPPERCASE, for now, the intent is to change this to highlight all matches found in the string. Hope you cna help me with this.

    [code]
    package anotherpackage;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    import javax.swing.JButton;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.BadLocationException;


    public class Test {
    private static String bigstr;
    private static Pattern patternP;
    private static Matcher matcherR;

    private static String previousText;

    public static void main(final String[] args) throws MalformedURLException {
    SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
    try {
    init();
    } catch (BadLocationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    });
    }

    private static void init() throws BadLocationException {
    final JFrame frame = new JFrame("WORD FINDER");
    frame.setVisible(true);
    frame.setSize(900,500);
    frame.setLayout(new BorderLayout());
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    Color color_ventana = new Color(190, 220, 170);
    frame.setBackground(color_ventana);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);




    final JTextArea textArea = new JTextArea();
    textArea.setFont( new Font ("Arial",Font.BOLD,40) );
    textArea.setSelectionColor(Color.RED);
    textArea.setSize(300, 500);
    textArea.setBackground(Color.lightGray);
    textArea.setForeground(Color.BLACK);


    patternP = Pattern.compile("Expression Goes Here");
    bigstr = "--------------";


    final JTextField Changepattern = new JTextField(20);
    Changepattern.setText(patternP.toString());
    Changepattern.setSize(20, 10);


    JScrollPane scroll = new JScrollPane (textArea,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    textArea.setText(bigstr);



    JPanel ButtonPanel = new JPanel();
    ButtonPanel.setLayout(new BorderLayout());

    JButton ExitButton = new JButton();
    ExitButton.setText("Exit");
    ExitButton.setFont( new Font ("Avenir",Font.ITALIC,40) );
    ExitButton.setForeground(Color.RED);
    ExitButton.setPreferredSize(new Dimension(150, 60));
    ExitButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
    frame.dispose();
    }

    });


    ButtonPanel.add(ExitButton, BorderLayout.CENTER);
    JButton Refresh = new JButton("Refresh");
    Refresh.setFont( new Font ("Avenir",Font.ITALIC,20) );
    Refresh.setForeground(Color.BLUE);
    Refresh.setPreferredSize(new Dimension(100, 40));

    //REFRESH
    Refresh.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed

    patternP = Pattern.compile(Changepattern.getText());
    textArea.setText(refreshBox(textArea, textArea.getText()));
    }

    }); frame.getRootPane().setDefaultButton(Refresh); //button highlighted por default

    JButton Revert = new JButton("Revert to Original");
    Revert.setFont( new Font ("Avenir",Font.ITALIC,15) );
    Revert.setForeground(Color.BLUE);
    Revert.setPreferredSize(new Dimension(160, 40));
    //REVERT TO ORIGINAL
    Revert.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed

    textArea.setText(previousText);
    }


    });




    JButton resetTextBox = new JButton("Clean Box");
    resetTextBox.setFont( new Font ("Avenir",Font.ITALIC,20) );
    resetTextBox.setForeground(Color.BLUE);
    resetTextBox.setPreferredSize(new Dimension(120, 40));
    resetTextBox.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed
    textArea.setText("");

    }
    });
    JPanel LabelPanel = new JPanel();

    LabelPanel.setSize(10, 40);

    JLabel ER = new JLabel("Regular Expression: ");
    ER.setFont( new Font ("Arial",Font.BOLD,20) );
    LabelPanel.add(ER, BorderLayout.CENTER);
    LabelPanel.add(Changepattern);
    LabelPanel.add(Refresh, BorderLayout.AFTER_LAST_LINE);
    LabelPanel.add(Revert, BorderLayout.AFTER_LAST_LINE);
    LabelPanel.add(resetTextBox, BorderLayout.AFTER_LAST_LINE);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setSize(textArea.getWidth(), textArea.getHeight());
    panel.setVisible(true);
    JLabel resultlabel = new JLabel("Results: ");
    resultlabel.setFont( new Font ("Avenir",Font.BOLD,20) );
    panel.add(resultlabel, BorderLayout.NORTH);

    panel.add(scroll, BorderLayout.CENTER);

    frame.add(LabelPanel, BorderLayout.PAGE_START);
    frame.add(panel, BorderLayout.CENTER);
    frame.add(ButtonPanel, BorderLayout.SOUTH);






    }







    public static String refreshBox(JTextArea area, String string) {
    // TODO Auto-generated method stub
    previousText = string;
    matcherR = patternP.matcher(string);


    String nuevoTexto = "";


    while(matcherR.find()){

    String str = matcherR.group().toString();

    nuevoTexto = str.toUpperCase();
    JLabel label4paint = new JLabel();

    label4paint.setText(nuevoTexto);


    label4paint.setForeground(Color.BLUE);



    }

    return area.getText();
    }





    }

    [/code][/QUOTE]

  4. #4
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,448

    Re: highlighning a pattern in TextArea, please help

    Something is wrong with the code tags. Please edit your post and retype them to get the formatting. The post should look like this:
    Code:
       Some code here
    Norm

  5. #5
    Join Date
    Nov 2013
    Posts
    4

    Re: highlighning a pattern in TextArea, please help

    Code:
    package anotherpackage;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import javax.swing.JButton;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.BadLocationException;
    
    
    public class Test {
    private static String bigstr;
    private static Pattern patternP;
    private static Matcher matcherR;
    
    private static String previousText;
    
    public static void main(final String[] args) throws MalformedURLException {
    SwingUtilities.invokeLater(new Runnable() {
    
    @Override
    public void run() {
    try {
    init();
    } catch (BadLocationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    
    }
    });
    }
    
    private static void init() throws BadLocationException {
    final JFrame frame = new JFrame("WORD FINDER");
    frame.setVisible(true);
    frame.setSize(900,500);
    frame.setLayout(new BorderLayout());
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    Color color_ventana = new Color(190, 220, 170);
    frame.setBackground(color_ventana);
    
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
    
    
    
    
    final JTextArea textArea = new JTextArea();
    textArea.setFont( new Font ("Arial",Font.BOLD,40) );
    textArea.setSelectionColor(Color.RED);
    textArea.setSize(300, 500);
    textArea.setBackground(Color.lightGray);
    textArea.setForeground(Color.BLACK);
    
    
    patternP = Pattern.compile("Expression Goes Here");
    bigstr = "--------------";
    
    
    final JTextField Changepattern = new JTextField(20);
    Changepattern.setText(patternP.toString());
    Changepattern.setSize(20, 10);
    
    
    JScrollPane scroll = new JScrollPane (textArea,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    
    textArea.setText(bigstr);
    
    
    
    JPanel ButtonPanel = new JPanel();
    ButtonPanel.setLayout(new BorderLayout());
    
    JButton ExitButton = new JButton();
    ExitButton.setText("Exit");
    ExitButton.setFont( new Font ("Avenir",Font.ITALIC,40) );
    ExitButton.setForeground(Color.RED);
    ExitButton.setPreferredSize(new Dimension(150, 60));
    ExitButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
    frame.dispose();
    }
    
    });
    
    
    ButtonPanel.add(ExitButton, BorderLayout.CENTER);
    JButton Refresh = new JButton("Refresh");
    Refresh.setFont( new Font ("Avenir",Font.ITALIC,20) );
    Refresh.setForeground(Color.BLUE);
    Refresh.setPreferredSize(new Dimension(100, 40));
    
    //REFRESH
    Refresh.addActionListener(new ActionListener() {
    
    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed
    
    patternP = Pattern.compile(Changepattern.getText());
    textArea.setText(refreshBox(textArea, textArea.getText()));
    }
    
    }); frame.getRootPane().setDefaultButton(Refresh); //button highlighted por default
    
    JButton Revert = new JButton("Revert to Original");
    Revert.setFont( new Font ("Avenir",Font.ITALIC,15) );
    Revert.setForeground(Color.BLUE);
    Revert.setPreferredSize(new Dimension(160, 40));
    //REVERT TO ORIGINAL
    Revert.addActionListener(new ActionListener() {
    
    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed
    
    textArea.setText(previousText);
    }
    
    
    });
    
    
    
    
    JButton resetTextBox = new JButton("Clean Box");
    resetTextBox.setFont( new Font ("Avenir",Font.ITALIC,20) );
    resetTextBox.setForeground(Color.BLUE);
    resetTextBox.setPreferredSize(new Dimension(120, 40));
    resetTextBox.addActionListener(new ActionListener() {
    
    public void actionPerformed(ActionEvent e)
    {
    //if button was pressed
    textArea.setText("");
    
    }
    });
    JPanel LabelPanel = new JPanel();
    
    LabelPanel.setSize(10, 40);
    
    JLabel ER = new JLabel("Regular Expression: ");
    ER.setFont( new Font ("Arial",Font.BOLD,20) );
    LabelPanel.add(ER, BorderLayout.CENTER);
    LabelPanel.add(Changepattern);
    LabelPanel.add(Refresh, BorderLayout.AFTER_LAST_LINE);
    LabelPanel.add(Revert, BorderLayout.AFTER_LAST_LINE);
    LabelPanel.add(resetTextBox, BorderLayout.AFTER_LAST_LINE);
    
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setSize(textArea.getWidth(), textArea.getHeight());
    panel.setVisible(true);
    JLabel resultlabel = new JLabel("Results: ");
    resultlabel.setFont( new Font ("Avenir",Font.BOLD,20) );
    panel.add(resultlabel, BorderLayout.NORTH);
    
    panel.add(scroll, BorderLayout.CENTER);
    
    frame.add(LabelPanel, BorderLayout.PAGE_START);
    frame.add(panel, BorderLayout.CENTER);
    frame.add(ButtonPanel, BorderLayout.SOUTH);
    
    
    
    
    
    
    }
    
    
    
    
    
    
    
    public static String refreshBox(JTextArea area, String string) {
    // TODO Auto-generated method stub
    previousText = string;
    matcherR = patternP.matcher(string);
    
    
    String nuevoTexto = "";
    
    
    while(matcherR.find()){
    
    String str = matcherR.group().toString();
    
    nuevoTexto = str.toUpperCase();
    JLabel label4paint = new JLabel();
    
    label4paint.setText(nuevoTexto);
    
    
    label4paint.setForeground(Color.BLUE);
    
    
    
    }
    
    return area.getText();
    }
    
    
    
    
    
    }

  6. #6
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,448

    Re: highlighning a pattern in TextArea, please help

    The code has lost all its formatting. All the statements start in the first column. Nested statements should be indented like this:
    Code:
       //  Following class for testing
       static class JOptionPaneXX {        //  3/12/13
          static String[] retVals = {"cat","felix", "5", "3"};  //  the responses to be returned by showInput
          static int idx = 0;  // index to above
    
          static public String showInputDialog(Object obj, String msg) {
             return showInputDialog(msg);
          }
          static public String showInputDialog(Object obj, String msg, String t, int i) {
             return showInputDialog(msg);
          }
       
    
          static public String showInputDialog(String msg) {
             System.out.println(msg + " >Return val="+retVals[idx]);
             return retVals[idx++];
          }
    
          static public void showMessageDialog(Object obj1, String msg) {
                System.out.println(msg);
          }
       
          static public void showMessageDialog(Object parent, Object msg, String title, int type) {
                System.out.println(msg);
          }
       
          static int INFORMATION_MESSAGE = 1;
          static int QUESTION_MESSAGE = 2;
          static int ERROR_MESSAGE = 3;
       }   //  end JOptionPane class for testing
    Norm

  7. #7
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,448

    Re: highlighning a pattern in TextArea, please help

    I don't see where the code has any highlighting code in it.
    Norm

  8. #8
    Join Date
    Nov 2013
    Posts
    4

    Re: highlighning a pattern in TextArea, please help

    Quote Originally Posted by Norm View Post
    I don't see where the code has any highlighting code in it.
    No Norm, it doesn't because I don't know how to use it, I've tried but it has all been in vain.
    I was hoping you could help me buy giving me an example or modifying a little bit my code. I just need the "line" or the important statements and functions to how to highlight all patterns found in the jtextarea.

  9. #9
    Join Date
    Jun 1999
    Location
    SW Missouri
    Posts
    3,448

    Re: highlighning a pattern in TextArea, please help

    Can you edit the code in code tags and restore its formatting?

    The first post has code for highlighting. I copied that into a program and it worked for me. These lines of code work:
    Code:
       redPainter = new DefaultHighlightPainter(Color.RED); 
       bluePainter = new DefaultHighlightPainter(Color.blue); 
    ...
    
    textArea.getHighlighter().addHighlight(2,5, redPainter);       //<<<<<<<<<<<<<<
    textArea.getHighlighter().addHighlight(12,17, bluePainter);       //<<<<<<<<<<<<<<
    The columns 2-5 and 12-17 were colored.
    Norm

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center