plz help me for this difficult project

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #16
    Originally posted by tamara omar
    no im gonna be with u all the way,but there r more than one error :
    tamara2.java=ca nt resolve symbol
    import java.util.Scann er ; and the error sign is under the S !!!
    No need to panic for that. That means you are using a jdk version that is not 1.5 and so your compiler does not recognise the scanner. I've just changed that to using a combination of BufferedReader and FileReader. I also figured you might want a saving functionality after replacing some words so I added that too.
    Code:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    import java.awt.Container;
    import java.io.*;
    import java.awt.*;
    //import java.util.Scanner;
    public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
    	private Container pane;
    	JTextArea area;
    	JFileChooser fc;
    	JPanel southPanel;
    	JPanel northPanel;
    	JScrollPane scrollPane;
    	static private final String newline = "\n";
    	public Tamara2() {
    		pane = getContentPane(); //pane will now replace getContentPane() from now onwards
    
    
    		setTitle("Tamara Omar");
    		setSize(400, 400);
    
    
    
    		//
    		fc = new JFileChooser();
    		area = new JTextArea(10,20);
    		scrollPane = new JScrollPane(area);
    
    		area.setMargin(new Insets(5,5,5,5));
    		area.setEditable(true);
    
    
    
    		//make buttons
    		JButton open = makeButton("Open");
    		JButton save = makeButton("Save");
    		JButton edit = makeButton("Find");
    		JButton edit1= makeButton("find all");
    		JButton replace1=makeButton("replace all");
    		JButton replace = makeButton("Replace");
    
    		southPanel = new JPanel();
    		northPanel = new JPanel();
    		//add the buttons to the panel
    		southPanel.add(edit1);
    		southPanel.add(replace1);
    		southPanel.add(edit);
    		southPanel.add(replace);
    		//add the panel to the frame at the bottom
    
    		northPanel.add(open);
    		northPanel.add(save);
    		pane.add(northPanel, "North");
    		pane.add(scrollPane, "Center");
    		pane.add(southPanel, "South");
    
    		setVisible(true);
    }
    public JButton makeButton(String label) { //creates a button
    	JButton jb = new JButton(label);
    	jb.setActionCommand(label); //This message will be set in the action for the button
    	jb.addActionListener(this); //this (JFrame) will respond to this button's press
    	return jb;
    }
    
    public void actionPerformed(ActionEvent action) {
    	String command = action.getActionCommand();
    	if(command.equals("Find")) {
    		JOptionPane.showMessageDialog(this, "Find");
    	}
    	else if(command.equals("Replace")) {
    		JOptionPane.showMessageDialog(this, "Replace");
    	}
    	else if(command.equals("replace all")) {
    		JOptionPane.showMessageDialog(this,"replace all");
    	}
    	else if(command.equals("find all"))	{
    		JOptionPane.showMessageDialog(this,"replace all");
    	}
    	else if(command.equals("Open")) {
    		int returnVal = fc.showOpenDialog(Tamara2.this);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			 File file = fc.getSelectedFile();
    			 //This is where a real application would open the file.
    			 //Scanner inFile = null;
    			 BufferedReader inFile = null;
    			 try {
    				 inFile = new BufferedReader(new FileReader(file));
    				 String line = "";
    				 while ((line = inFile.readLine()) != null) {
    					//String line = inFile.readLine();
    					area.append(line + newline);
    				 }
    				 inFile.close();
    		 	 }
    		 	 catch(IOException iOE) {
    			 			 	iOE.printStackTrace();
    			 }
    	 	 }
    	 	 else {
    			 area.append("Open command cancelled by user." + newline);
    		 }
    		 area.setCaretPosition(area.getDocument().getLength());
    	}
    	else if(command.equals("Save")) {
    		try {
    			int returnVal = fc.showSaveDialog(Tamara2.this);
    			if(returnVal == JFileChooser.APPROVE_OPTION) {
    				File file = fc.getSelectedFile();
    				//FileOutputStream fos = new FileOutputStream(file);
    				//DataOutputStream dos = new DataOutputStream(fos);
    				BufferedWriter out = new BufferedWriter(new FileWriter(file));
    
    				//This is where a real application would save the file.
    
    				int rows = area.getLineCount();
    
    				for(int i = 0; i < rows; i++) {
    					int end = area.getLineEndOffset(i);
    					int start = area.getLineStartOffset(i);
    					int length = end - start;
    					if(length <= 0) {
    						length = 1;
    					}
    					String s = area.getText(start, (length-1));
    					System.out.println(s);
    					out.write(s);
    					out.newLine();
    					out.flush();
    
    				}
    				out.close();
    
    				area.append("Saving: " + file.getName() + "." + newline);
    			}
    			else {
    				area.append("Save command cancelled by user." + newline);
    			}
    		}
    		catch(Exception e) {
    			e.printStackTrace();
    		}
    		area.setCaretPosition(area.getDocument().getLength());
    	}
    
    
    }
    
    
    public static void main(String[] args) {
    	new Tamara2();
    	}
    }

    Comment

    • tamara omar
      New Member
      • Sep 2006
      • 23

      #17
      the compiler gives me no error but when i come to execute it gives me this msg:
      exception in thread "main" java.lang.NoCla ssDefFoundError :Tamara

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #18
        Originally posted by tamara omar
        the compiler gives me no error but when i come to execute it gives me this msg:
        exception in thread "main" java.lang.NoCla ssDefFoundError :Tamara
        Did you change the name of the class? I have no problem with it here.

        Comment

        • tamara omar
          New Member
          • Sep 2006
          • 23

          #19
          ok done,but i have a question ,when the user choose open command it will open his files on his computer ,right?
          now what next

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #20
            Originally posted by tamara omar
            ok done,but i have a question ,when the user choose open command it will open his files on his computer ,right?
            now what next
            The user can search for words that he/she types in on the textarea or search for words in a file on their computer. Here is an example with the find button. Note all the changes made to the code so far. Please make sure you are analysing the approach critically and try to spot some improvements.
            Code:
             import javax.swing.*;
            import javax.swing.text.*;
            import java.awt.event.*;
            import java.awt.Container;
            import java.io.*;
            import java.awt.*;
            import java.util.ArrayList;
            public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
            	private Container pane;
            	JTextArea area;
            	JFileChooser fc;
            	JPanel southPanel;
            	JPanel northPanel;
            	JPanel fieldsPanel;
            	JPanel buttonsPanel;
            	JScrollPane scrollPane;
            	JTextField findText;
            	JTextField replaceText;
            	static private final String newline = "\n";
            
            	private int lastPosition = 0;
            	public Tamara2() {
            		pane = getContentPane(); //pane will now replace getContentPane() from now onwards
            		setTitle("Tamara Omar");
            		setSize(400, 400);
            //
            		fc = new JFileChooser();
            		area = new JTextArea(10,20);
            		area.setDocument(new DefaultStyledDocument());
            		scrollPane = new JScrollPane(area);
            
            		area.setMargin(new Insets(5,5,5,5));
            		area.setEditable(true);
            
            		//make buttons
            		JButton open = makeButton("Open");
            		JButton save = makeButton("Save");
            		JButton edit = makeButton("Find");
            		JButton findAll = makeButton("Find All");
            		JButton replaceAll = makeButton("Replace All");
            		JButton replace = makeButton("Replace");
            		findText = new JTextField(10);
            		replaceText = new JTextField(10);
            
            
            		southPanel = new JPanel();
            		northPanel = new JPanel();
            		fieldsPanel = new JPanel();
            		buttonsPanel = new JPanel();
            		southPanel.setLayout(new GridLayout(2, 1));
            		//add the buttons to the panel
            		buttonsPanel.add(findAll);
            		buttonsPanel.add(replaceAll);
            		buttonsPanel.add(edit);
            		buttonsPanel.add(replace);
            
            		//add the fields to the panel
            		fieldsPanel.add(new JLabel("Find:"));
            		fieldsPanel.add(findText);
            		fieldsPanel.add(new JLabel("Replace with:"));
            		fieldsPanel.add(replaceText);
            
            
            		//add the panel to the frame at the bottom
            		southPanel.add(fieldsPanel);
            		southPanel.add(buttonsPanel);
            
            		northPanel.add(open);
            		northPanel.add(save);
            		pane.add(northPanel, "North");
            		pane.add(scrollPane, "Center");
            		pane.add(southPanel, "South");
            
            		setVisible(true);
            }
            public JButton makeButton(String label) { //creates a button
            	JButton jb = new JButton(label);
            	jb.setActionCommand(label); //This message will be set in the action for the button
            	jb.addActionListener(this); //this (JFrame) will respond to this button's press
            	return jb;
            }
            
            public void actionPerformed(ActionEvent action) {
            	String command = action.getActionCommand();
            	if(command.equals("Find")) {
            		area.setSelectedTextColor(Color.blue);
            		String searchString = findText.getText();
            		ArrayList matches = findAll(area, searchString);
            		if(matches.size() == 0) {
            			JOptionPane.showMessageDialog(this, searchString+" Was not found");
            		}
            		else {
            			for(int i = 0; i < matches.size(); i++) {
            				int x = (int)(Integer)matches.get(i);
            				area.setCaretPosition(x);
            				area.moveCaretPosition(x + searchString.length());
            				area.requestFocus();
            
            			}
            		}
            	}
            	else if(command.equals("Replace")) {
            		JOptionPane.showMessageDialog(this, "Replace");
            	}
            	else if(command.equals("Replace All")) {
            		JOptionPane.showMessageDialog(this,"Replace All");
            	}
            	else if(command.equals("Find All"))	{
            		JOptionPane.showMessageDialog(this,"Find All");
            	}
            	else if(command.equals("Open")) {
            		int returnVal = fc.showOpenDialog(Tamara2.this);
            		if (returnVal == JFileChooser.APPROVE_OPTION) {
            			 File file = fc.getSelectedFile();
            			 BufferedReader inFile = null;
            			 try {
            				 inFile = new BufferedReader(new FileReader(file));
            				 String line = "";
            				 while ((line = inFile.readLine()) != null) {
            					area.append(line + newline);
            				 }
            				 inFile.close();
            		 	 }
            		 	 catch(IOException iOE) {
            			 			 	iOE.printStackTrace();
            			 }
            	 	 }
            	 	 else {
            			 area.append("Open command cancelled by user." + newline);
            		 }
            
            	}
            	else if(command.equals("Save")) {
            		try {
            			int returnVal = fc.showSaveDialog(Tamara2.this);
            			if(returnVal == JFileChooser.APPROVE_OPTION) {
            				File file = fc.getSelectedFile();
            				BufferedWriter out = new BufferedWriter(new FileWriter(file));
            				int rows = area.getLineCount();
            				for(int i = 0; i < rows; i++) {
            					int end = area.getLineEndOffset(i);
            					int start = area.getLineStartOffset(i);
            					int length = end - start;
            					if(length <= 0) {
            						length = 1;
            					}
            					String s = area.getText(start, (length-1));
            					out.write(s);
            					out.newLine();
            					out.flush();
            
            				}
            				out.close();
            
            
            			}
            			else {
            				area.append("Save command cancelled by user." + newline);
            			}
            		}
            		catch(Exception e) {
            			e.printStackTrace();
            		}
            		area.setCaretPosition(area.getDocument().getLength());
            	}
            
            
            }
            public ArrayList findAll(JTextArea area, String text) {
            	ArrayList startPositions = new ArrayList();
            	int length = text.length();
            	int rows = area.getLineCount();
            	try {
            		int all = area.getLineEndOffset((rows - 1));
            		for(int i = 0; i < (all - length); i++) {
            			String x = area.getText(i, length);
            			if(x.equalsIgnoreCase(text)) {
            				startPositions.add(new Integer(i));
            			}
            		}
            	}
            	catch(BadLocationException e) {
            		e.printStackTrace();
            	}
            	return startPositions;
            
            }
            
            
            public static void main(String[] args) {
            	new Tamara2();
            	}
            }

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #21
              Hey Tamara if you are still there, you might have noticed that the search I've done is actually for findAll. So edit the actionPerformed method to something like this
              Code:
              public void actionPerformed(ActionEvent action) {
              	String command = action.getActionCommand();
              	if(command.equals("Find")) {
              		JOptionPane.showMessageDialog(this,"Find");
              	}
              	else if(command.equals("Replace")) {
              		JOptionPane.showMessageDialog(this, "Replace");
              	}
              	else if(command.equals("Replace All")) {
              		JOptionPane.showMessageDialog(this,"Replace All");
              	}
              	else if(command.equals("Find All"))	{
              		area.setSelectedTextColor(Color.blue);
              		String searchString = findText.getText();
              		ArrayList matches = findAll(area, searchString);
              		if(matches.size() == 0) {
              			JOptionPane.showMessageDialog(this, searchString+" Was not found");
              		}
              		else {
              			try {
              				for(int i = 0; i < matches.size(); i++) {
              					int x = (int)(Integer)matches.get(i);
              					//area.setCaretPosition(x);
              					//area.moveCaretPosition(x + searchString.length());
              					int z = x + searchString.length();
              					area.getHighlighter().addHighlight(x, z, new DefaultHighlighter.DefaultHighlightPainter(Color.blue));
              					area.requestFocus();
              				}
              			}
              			catch(Exception e) {
              				e.printStackTrace();
              			}
              
              		}
              
              	}
              	else if(command.equals("Open")) {
              The Find all button should be the one activated now and should now be selecting all occurrences of the search string. If you've done that right then that will be as far as we will go today. Unless you have any questions concerning what we've done so far?

              Comment

              • tamara omar
                New Member
                • Sep 2006
                • 23

                #22
                i hate the errors ,
                tamara2.java:94 : inconvertable types
                found:java.lang .integer
                required:int int x=(int)(Integer )matches.get(i) ;

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #23
                  Originally posted by tamara omar
                  i hate the errors ,
                  tamara2.java:94 : inconvertable types
                  found:java.lang .integer
                  required:int int x=(int)(Integer )matches.get(i) ;
                  Must be the 1.5 autoboxing that is not available on your compiler.
                  change the line to
                  Code:
                  int x = ((Integer)matches.get(i)).intValue();
                  The more errors one gets, the better one gets at programming so they are not too bad after all.

                  Comment

                  • tamara omar
                    New Member
                    • Sep 2006
                    • 23

                    #24
                    it still the replace and replace all doesnt work,and when i open any file it doesnt appear in the text area, and there is an important thing which is these packages should be included (they are for searching as regular expressions u know like we can put in the search area /much/ so it brings much or /[abcd]/ so it matches a or b or c or d !!! i think these packages for this use)
                    import java.util.regex .Matcher;
                    import java.util.regex .Pattern;
                    import java.util.Strin gTokenizer;
                    import java.util.Vecto r;
                    import java.io.*;

                    this is the latest version from our program :)
                    import javax.swing.*;
                    import javax.swing.tex t.*;
                    import java.awt.event. *;
                    import java.awt.Contai ner;
                    import java.io.*;
                    import java.awt.*;
                    import java.util.Array List;
                    public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                    private Container pane;
                    JTextArea area;
                    JFileChooser fc;
                    JPanel southPanel;
                    JPanel northPanel;
                    JPanel fieldsPanel;
                    JPanel buttonsPanel;
                    JScrollPane scrollPane;
                    JTextField findText;
                    JTextField replaceText;
                    static private final String newline = "\n";

                    private int lastPosition = 0;
                    public Tamara2() {
                    pane = getContentPane( ); //pane will now replace getContentPane( ) from now onwards
                    setTitle("Tamar a Omar");
                    setSize(400, 400);
                    //
                    fc = new JFileChooser();
                    area = new JTextArea(10,20 );
                    area.setDocumen t(new DefaultStyledDo cument());
                    scrollPane = new JScrollPane(are a);

                    area.setMargin( new Insets(5,5,5,5) );
                    area.setEditabl e(true);

                    //make buttons
                    JButton open = makeButton("Ope n");
                    JButton save = makeButton("Sav e");
                    JButton edit = makeButton("Fin d");
                    JButton findAll = makeButton("Fin d All");
                    JButton replaceAll = makeButton("Rep lace All");
                    JButton replace = makeButton("Rep lace");
                    findText = new JTextField(10);
                    replaceText = new JTextField(10);


                    southPanel = new JPanel();
                    northPanel = new JPanel();
                    fieldsPanel = new JPanel();
                    buttonsPanel = new JPanel();
                    southPanel.setL ayout(new GridLayout(2, 1));
                    //add the buttons to the panel
                    buttonsPanel.ad d(findAll);
                    buttonsPanel.ad d(replaceAll);
                    buttonsPanel.ad d(edit);
                    buttonsPanel.ad d(replace);

                    //add the fields to the panel
                    fieldsPanel.add (new JLabel("Find:") );
                    fieldsPanel.add (findText);
                    fieldsPanel.add (new JLabel("Replace with:"));
                    fieldsPanel.add (replaceText);


                    //add the panel to the frame at the bottom
                    southPanel.add( fieldsPanel);
                    southPanel.add( buttonsPanel);

                    northPanel.add( open);
                    northPanel.add( save);
                    pane.add(northP anel, "North");
                    pane.add(scroll Pane, "Center");
                    pane.add(southP anel, "South");

                    setVisible(true );
                    }
                    public JButton makeButton(Stri ng label) { //creates a button
                    JButton jb = new JButton(label);
                    jb.setActionCom mand(label); //This message will be set in the action for the button
                    jb.addActionLis tener(this); //this (JFrame) will respond to this button's press
                    return jb;
                    }

                    public void actionPerformed (ActionEvent action) {
                    String command = action.getActio nCommand();
                    if(command.equa ls("Find")) {
                    area.setSelecte dTextColor(Colo r.blue);
                    String searchString = findText.getTex t();
                    ArrayList matches = findAll(area, searchString);
                    if(matches.size () == 0) {
                    JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                    }
                    else {
                    for(int i = 0; i < matches.size(); i++) {
                    int x = ((Integer)match es.get(i)).intV alue();
                    area.setCaretPo sition(x);
                    area.moveCaretP osition(x + searchString.le ngth());
                    area.requestFoc us();

                    }
                    }
                    }
                    else if(command.equa ls("Replace")) {
                    area.setSelecte dTextColor(Colo r.blue);
                    String searchString = findText.getTex t();
                    ArrayList matches = findAll(area, searchString);
                    if(matches.size () == 0) {
                    JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                    }
                    else {
                    for(int i = 0; i < matches.size(); i++) {
                    int x = ((Integer)match es.get(i)).intV alue();
                    area.setCaretPo sition(x);
                    area.moveCaretP osition(x + searchString.le ngth());
                    area.requestFoc us();

                    }
                    }

                    }
                    else if(command.equa ls("Replace All")) { area.setSelecte dTextColor(Colo r.blue);
                    String searchString = findText.getTex t();
                    ArrayList matches = findAll(area, searchString);
                    if(matches.size () == 0) {
                    JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                    }
                    else {
                    for(int i = 0; i < matches.size(); i++) {
                    int x = ((Integer)match es.get(i)).intV alue();
                    area.setCaretPo sition(x);
                    area.moveCaretP osition(x + searchString.le ngth());
                    area.requestFoc us();

                    }
                    }

                    }
                    else if(command.equa ls("Find All")) { area.setSelecte dTextColor(Colo r.blue);
                    String searchString = findText.getTex t();
                    ArrayList matches = findAll(area, searchString);
                    if(matches.size () == 0) {
                    JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                    }
                    else {
                    for(int i = 0; i < matches.size(); i++) {
                    int x = ((Integer)match es.get(i)).intV alue();
                    area.setCaretPo sition(x);
                    area.moveCaretP osition(x + searchString.le ngth());
                    area.requestFoc us();

                    }
                    }

                    }
                    else if(command.equa ls("Open")) {
                    int returnVal = fc.showOpenDial og(Tamara2.this );
                    if (returnVal == JFileChooser.AP PROVE_OPTION) {
                    File file = fc.getSelectedF ile();
                    BufferedReader inFile = null;
                    try {
                    inFile = new BufferedReader( new FileReader(file ));
                    String line = "";
                    while ((line = inFile.readLine ()) != null) {
                    area.append(lin e + newline);
                    }
                    inFile.close();
                    }
                    catch(IOExcepti on iOE) {
                    iOE.printStackT race();
                    }
                    }
                    else {
                    area.append("Op en command cancelled by user." + newline);
                    }

                    }
                    else if(command.equa ls("Save")) {
                    try {
                    int returnVal = fc.showSaveDial og(Tamara2.this );
                    if(returnVal == JFileChooser.AP PROVE_OPTION) {
                    File file = fc.getSelectedF ile();
                    BufferedWriter out = new BufferedWriter( new FileWriter(file ));
                    int rows = area.getLineCou nt();
                    for(int i = 0; i < rows; i++) {
                    int end = area.getLineEnd Offset(i);
                    int start = area.getLineSta rtOffset(i);
                    int length = end - start;
                    if(length <= 0) {
                    length = 1;
                    }
                    String s = area.getText(st art, (length-1));
                    out.write(s);
                    out.newLine();
                    out.flush();

                    }
                    out.close();


                    }
                    else {
                    area.append("Sa ve command cancelled by user." + newline);
                    }
                    }
                    catch(Exception e) {
                    e.printStackTra ce();
                    }
                    area.setCaretPo sition(area.get Document().getL ength ());
                    }


                    }
                    public ArrayList findAll(JTextAr ea area, String text) {
                    ArrayList startPositions = new ArrayList();
                    int length = text.length();
                    int rows = area.getLineCou nt();
                    try {
                    int all = area.getLineEnd Offset((rows - 1));
                    for(int i = 0; i < (all - length); i++) {
                    String x = area.getText(i, length);
                    if(x.equalsIgno reCase(text)) {
                    startPositions. add(new Integer(i));
                    }
                    }
                    }
                    catch(BadLocati onException e) {
                    e.printStackTra ce();
                    }
                    return startPositions;

                    }


                    public static void main(String[] args) {
                    new Tamara2();
                    }
                    }

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #25
                      it still the replace and replace all doesnt work,and when i open any file it doesnt appear in the text area, and there is an important thing which is these packages should be included (they are for searching as regular expressions u know like we can put in the search area /much/ so it brings much or /[abcd]/ so it matches a or b or c or d !!! i think these packages for this use)
                      import java.util.regex .Matcher;
                      import java.util.regex .Pattern;
                      import java.util.Strin gTokenizer;
                      import java.util.Vecto r;
                      import java.io.*;
                      The classes in java.util.regex are for regular expressions. We will use these to do the search in the find, findAll, methods. You should look at the following to get a good understanding of regular expressions. I had not used them yet because I thought you might not have had a chance to look at them yet.
                      These are probably the best resources for them: http://java.sun.com/developer/technicalArticl es/releases/1.4regex/
                      http://java.sun.com/docs/books/tutorial/essential/regex/
                      If you look at this you will realise that use of regular expressions replaces StringTokenizer and so there is no point in using both of them.
                      Concerning the Vector, is it absolutely neccessary that it be used because it's one of those classes (like StringTokenizer ) which should now be avoided. I have used ArrayList instead but can always replace it with vector if you really must use the vector.

                      What type of files are refusing to be opened in the text area? I can open .txt, .java, .doc(text only),. Remember we only want to search for text.

                      You seem to have misunderstood the last post. Only the findAll is supposed to be working right now. The current should be something like this:

                      Code:
                      import javax.swing.*;
                      import javax.swing.text.*;
                      import java.awt.event.*;
                      import java.awt.Container;
                      import java.io.*;
                      import java.awt.*;
                      import java.util.ArrayList;
                      public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                      	private Container pane;
                      	JTextArea area;
                      	JFileChooser fc;
                      	JPanel southPanel;
                      	JPanel northPanel;
                      	JPanel fieldsPanel;
                      	JPanel buttonsPanel;
                      	JScrollPane scrollPane;
                      	JTextField findText;
                      	JTextField replaceText;
                      	static private final String newline = "\n";
                      
                      	private int lastPosition = 0;
                      	public Tamara2() {
                      		pane = getContentPane(); //pane will now replace getContentPane() from now onwards
                      		setTitle("Tamara Omar");
                      		setSize(400, 400);
                      //
                      		fc = new JFileChooser();
                      		area = new JTextArea(10,20);
                      		area.setDocument(new DefaultStyledDocument());
                      		scrollPane = new JScrollPane(area);
                      
                      		area.setMargin(new Insets(5,5,5,5));
                      		area.setEditable(true);
                      
                      		//make buttons
                      		JButton open = makeButton("Open");
                      		JButton save = makeButton("Save");
                      		JButton edit = makeButton("Find");
                      		JButton findAll = makeButton("Find All");
                      		JButton replaceAll = makeButton("Replace All");
                      		JButton replace = makeButton("Replace");
                      		findText = new JTextField(10);
                      		replaceText = new JTextField(10);
                      
                      
                      		southPanel = new JPanel();
                      		northPanel = new JPanel();
                      		fieldsPanel = new JPanel();
                      		buttonsPanel = new JPanel();
                      		southPanel.setLayout(new GridLayout(2, 1));
                      		//add the buttons to the panel
                      		buttonsPanel.add(findAll);
                      		buttonsPanel.add(replaceAll);
                      		buttonsPanel.add(edit);
                      		buttonsPanel.add(replace);
                      
                      		//add the fields to the panel
                      		fieldsPanel.add(new JLabel("Find:"));
                      		fieldsPanel.add(findText);
                      		fieldsPanel.add(new JLabel("Replace with:"));
                      		fieldsPanel.add(replaceText);
                      
                      
                      		//add the panel to the frame at the bottom
                      		southPanel.add(fieldsPanel);
                      		southPanel.add(buttonsPanel);
                      
                      		northPanel.add(open);
                      		northPanel.add(save);
                      		pane.add(northPanel, "North");
                      		pane.add(scrollPane, "Center");
                      		pane.add(southPanel, "South");
                      
                      		setVisible(true);
                      }
                      public JButton makeButton(String label) { //creates a button
                      	JButton jb = new JButton(label);
                      	jb.setActionCommand(label); //This message will be set in the action for the button
                      	jb.addActionListener(this); //this (JFrame) will respond to this button's press
                      	return jb;
                      }
                      
                      public void actionPerformed(ActionEvent action) {
                      	String command = action.getActionCommand();
                      	if(command.equals("Find")) {
                      		JOptionPane.showMessageDialog(this,"Find");
                      	}
                      	else if(command.equals("Replace")) {
                      		JOptionPane.showMessageDialog(this, "Replace");
                      	}
                      	else if(command.equals("Replace All")) {
                      		JOptionPane.showMessageDialog(this,"Replace All");
                      	}
                      	else if(command.equals("Find All"))	{
                      		area.setSelectedTextColor(Color.blue);
                      		String searchString = findText.getText();
                      		ArrayList matches = findAll(area, searchString);
                      		if(matches.size() == 0) {
                      			JOptionPane.showMessageDialog(this, searchString+" Was not found");
                      		}
                      		else {
                      			try {
                      				for(int i = 0; i < matches.size(); i++) {
                      					int x = ((Integer)matches.get(i)).intValue();
                      					//area.setCaretPosition(x);
                      					//area.moveCaretPosition(x + searchString.length());
                      					int z = x + searchString.length();
                      					area.getHighlighter().addHighlight(x, z, new DefaultHighlighter.DefaultHighlightPainter(Color.blue));
                      					area.requestFocus();
                      				}
                      				JOptionPane.showMessageDialog(this, "'"+searchString+"' was found " + matches.size() + " times");
                      			}
                      			catch(Exception e) {
                      				e.printStackTrace();
                      			}
                      
                      		}
                      
                      	}
                      	else if(command.equals("Open")) {
                      		int returnVal = fc.showOpenDialog(Tamara2.this);
                      		if (returnVal == JFileChooser.APPROVE_OPTION) {
                      			 File file = fc.getSelectedFile();
                      			 BufferedReader inFile = null;
                      			 try {
                      				 inFile = new BufferedReader(new FileReader(file));
                      				 String line = "";
                      				 while ((line = inFile.readLine()) != null) {
                      					area.append(line + newline);
                      				 }
                      				 inFile.close();
                      		 	 }
                      		 	 catch(IOException iOE) {
                      			 			 	iOE.printStackTrace();
                      			 }
                      	 	 }
                      	 	 else {
                      			 area.append("Open command cancelled by user." + newline);
                      		 }
                      
                      	}
                      	else if(command.equals("Save")) {
                      		try {
                      			int returnVal = fc.showSaveDialog(Tamara2.this);
                      			if(returnVal == JFileChooser.APPROVE_OPTION) {
                      				File file = fc.getSelectedFile();
                      				BufferedWriter out = new BufferedWriter(new FileWriter(file));
                      				int rows = area.getLineCount();
                      				for(int i = 0; i < rows; i++) {
                      					int end = area.getLineEndOffset(i);
                      					int start = area.getLineStartOffset(i);
                      					int length = end - start;
                      					if(length <= 0) {
                      						length = 1;
                      					}
                      					String s = area.getText(start, (length-1));
                      					out.write(s);
                      					out.newLine();
                      					out.flush();
                      
                      				}
                      				out.close();
                      
                      
                      			}
                      			else {
                      				area.append("Save command cancelled by user." + newline);
                      			}
                      		}
                      		catch(Exception e) {
                      			e.printStackTrace();
                      		}
                      		area.setCaretPosition(area.getDocument().getLength());
                      	}
                      
                      
                      }
                      
                      //********To change to Match using regular expressions*(return vector instead of ArrayList?)*********************
                      public ArrayList findAll(JTextArea area, String text) {
                      	ArrayList startPositions = new ArrayList();
                      	int length = text.length();
                      	int rows = area.getLineCount();
                      	try {
                      		int all = area.getLineEndOffset((rows - 1));
                      		for(int i = 0; i < (all - length); i++) {
                      			String x = area.getText(i, length);
                      			if(x.equalsIgnoreCase(text)) {
                      				startPositions.add(new Integer(i));
                      			}
                      		}
                      	}
                      	catch(BadLocationException e) {
                      		e.printStackTrace();
                      	}
                      	return startPositions;
                      
                      }
                      
                      
                      public static void main(String[] args) {
                      	new Tamara2();
                      	}
                      }
                      FindAll is supposed to load the start positions of the found words in the ArrayList(Vecto r). After you've gone through the fisrt of those regex tutorials, try to write and post an implementation of findAll that uses regular expressions. If you take more than 2 hours to get it right, just post what you'll have then and we'll look at it together.

                      Comment

                      • r035198x
                        MVP
                        • Sep 2006
                        • 13225

                        #26
                        Sounds like you are begginning to panick so here is the ReplaceAll that uses regular expressions.

                        1) add
                        Code:
                        import java.util.regex.*;
                        to the list of imports.

                        2) add the following method to the class

                        Code:
                        //************Does a replace all based on regular expressions*******************
                        public void replaceAll(JTextArea area, String find, String replace) {
                        	 Pattern p = Pattern.compile(find);
                        
                        	Matcher m = p.matcher(area.getText());
                        	StringBuffer sb = new StringBuffer();
                        	boolean result = m.find();
                        	while(result) {
                        		m.appendReplacement(sb, replace);
                        		result = m.find();
                        	}
                        	m.appendTail(sb);
                        	area.setText(sb.toString());
                        
                        }
                        3.) the n command for replace all
                        Code:
                        else if(command.equals("Replace All")) {
                               String find = findText.getText();
                               String replace = replaceText.getText();
                               replaceAll(area, find, replace);
                               area.requestFocus();
                               //JOptionPane.showMessageDialog(this,"Replace All");
                        }

                        Comment

                        • tamara omar
                          New Member
                          • Sep 2006
                          • 23

                          #27
                          import javax.swing.*;
                          import javax.swing.tex t.*;
                          import java.awt.event. *;
                          import java.awt.Contai ner;
                          import java.io.*;
                          import java.awt.*;
                          import java.util.Array List;
                          import java.util.regex .*;
                          public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                          private Container pane;
                          JTextArea area;
                          JFileChooser fc;
                          JPanel southPanel;
                          JPanel northPanel;
                          JPanel fieldsPanel;
                          JPanel buttonsPanel;
                          JScrollPane scrollPane;
                          JTextField findText;
                          JTextField replaceText;
                          static private final String newline = "\n";

                          private int lastPosition = 0;
                          public Tamara2() {
                          pane = getContentPane( ); //pane will now replace getContentPane( ) from now onwards
                          setTitle("Tamar a Omar");
                          setSize(400, 400);
                          //
                          fc = new JFileChooser();
                          area = new JTextArea(10,20 );
                          area.setDocumen t(new DefaultStyledDo cument());
                          scrollPane = new JScrollPane(are a);

                          area.setMargin( new Insets(5,5,5,5) );
                          area.setEditabl e(true);

                          //make buttons
                          JButton open = makeButton("Ope n");
                          JButton save = makeButton("Sav e");
                          JButton edit = makeButton("Fin d");
                          JButton findAll = makeButton("Fin d All");
                          JButton replaceAll = makeButton("Rep lace All");
                          JButton replace = makeButton("Rep lace");
                          findText = new JTextField(10);
                          replaceText = new JTextField(10);


                          southPanel = new JPanel();
                          northPanel = new JPanel();
                          fieldsPanel = new JPanel();
                          buttonsPanel = new JPanel();
                          southPanel.setL ayout(new GridLayout(2, 1));
                          //add the buttons to the panel
                          buttonsPanel.ad d(findAll);
                          buttonsPanel.ad d(replaceAll);
                          buttonsPanel.ad d(edit);
                          buttonsPanel.ad d(replace);

                          //add the fields to the panel
                          fieldsPanel.add (new JLabel("Find:") );
                          fieldsPanel.add (findText);
                          fieldsPanel.add (new JLabel("Replace with:"));
                          fieldsPanel.add (replaceText);


                          //add the panel to the frame at the bottom
                          southPanel.add( fieldsPanel);
                          southPanel.add( buttonsPanel);

                          northPanel.add( open);
                          northPanel.add( save);
                          pane.add(northP anel, "North");
                          pane.add(scroll Pane, "Center");
                          pane.add(southP anel, "South");

                          setVisible(true );
                          }
                          public JButton makeButton(Stri ng label) { //creates a button
                          JButton jb = new JButton(label);
                          jb.setActionCom mand(label); //This message will be set in the action for the button
                          jb.addActionLis tener(this); //this (JFrame) will respond to this button's press
                          return jb;
                          }

                          public void actionPerformed (ActionEvent action) {
                          String command = action.getActio nCommand();
                          if(command.equa ls("Find")) {
                          area.setSelecte dTextColor(Colo r.blue);
                          String searchString = findText.getTex t();
                          ArrayList matches = findAll(area, searchString);
                          if(matches.size () == 0) {
                          JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                          }
                          else {
                          for(int i = 0; i < matches.size(); i++) {
                          int x = ((Integer)match es.get(i)).intV alue();
                          area.setCaretPo sition(x);
                          area.moveCaretP osition(x + searchString.le ngth());
                          area.requestFoc us();

                          }
                          }
                          }
                          else if(command.equa ls("Replace")) {
                          area.setSelecte dTextColor(Colo r.blue);
                          String searchString = findText.getTex t();
                          ArrayList matches = findAll(area, searchString);
                          if(matches.size () == 0) {
                          JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                          }
                          else {
                          for(int i = 0; i < matches.size(); i++) {
                          int x = ((Integer)match es.get(i)).intV alue();
                          area.setCaretPo sition(x);
                          area.moveCaretP osition(x + searchString.le ngth());
                          area.requestFoc us();

                          }
                          }

                          }
                          else if(command.equa ls("Replace All")) {
                          String find = findText.getTex t();
                          String replace = replaceText.get Text();
                          replaceAll(area , find, replace);
                          area.requestFoc us();
                          //JOptionPane.sho wMessageDialog( this,"Replace All");
                          }

                          }
                          else if(command.equa ls("Find All")) { area.setSelecte dTextColor(Colo r.blue);
                          String searchString = findText.getTex t();
                          ArrayList matches = findAll(area, searchString);
                          if(matches.size () == 0) {
                          JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                          }
                          else {
                          for(int i = 0; i < matches.size(); i++) {
                          int x = ((Integer)match es.get(i)).intV alue();
                          area.setCaretPo sition(x);
                          area.moveCaretP osition(x + searchString.le ngth());
                          area.requestFoc us();

                          }
                          }

                          }
                          else if(command.equa ls("Open")) {
                          int returnVal = fc.showOpenDial og(Tamara2.this );
                          if (returnVal == JFileChooser.AP PROVE_OPTION) {
                          File file = fc.getSelectedF ile();
                          BufferedReader inFile = null;
                          try {
                          inFile = new BufferedReader( new FileReader(file ));
                          String line = "";
                          while ((line = inFile.readLine ()) != null) {
                          area.append(lin e + newline);
                          }
                          inFile.close();
                          }
                          catch(IOExcepti on iOE) {
                          iOE.printStackT race();
                          }
                          }
                          else {
                          area.append("Op en command cancelled by user." + newline);
                          }

                          }
                          else if(command.equa ls("Save")) {
                          try {
                          int returnVal = fc.showSaveDial og(Tamara2.this );
                          if(returnVal == JFileChooser.AP PROVE_OPTION) {
                          File file = fc.getSelectedF ile();
                          BufferedWriter out = new BufferedWriter( new FileWriter(file ));
                          int rows = area.getLineCou nt();
                          for(int i = 0; i < rows; i++) {
                          int end = area.getLineEnd Offset(i);
                          int start = area.getLineSta rtOffset(i);
                          int length = end - start;
                          if(length <= 0) {
                          length = 1;
                          }
                          String s = area.getText(st art, (length-1));
                          out.write(s);
                          out.newLine();
                          out.flush();

                          }
                          out.close();


                          }
                          else {
                          area.append("Sa ve command cancelled by user." + newline);
                          }
                          }
                          catch(Exception e) {
                          e.printStackTra ce();
                          }
                          area.setCaretPo sition(area.get Document().getL ength ());
                          }


                          }
                          public ArrayList findAll(JTextAr ea area, String text) {
                          ArrayList startPositions = new ArrayList();
                          int length = text.length();
                          int rows = area.getLineCou nt();
                          try {
                          int all = area.getLineEnd Offset((rows - 1));
                          for(int i = 0; i < (all - length); i++) {
                          String x = area.getText(i, length);
                          if(x.equalsIgno reCase(text)) {
                          startPositions. add(new Integer(i));
                          }
                          }
                          }
                          catch(BadLocati onException e) {
                          e.printStackTra ce();
                          }
                          return startPositions;

                          }
                          public void replaceAll(JTex tArea area, String find, String replace) {
                          Pattern p = Pattern.compile (find);

                          Matcher m = p.matcher(area. getText());
                          StringBuffer sb = new StringBuffer();
                          boolean result = m.find();
                          while(result) {
                          m.appendReplace ment(sb, replace);
                          result = m.find();
                          }
                          m.appendTail(sb );
                          area.setText(sb .toString());

                          }


                          public static void main(String[] args) {
                          new Tamara2();
                          }
                          }



                          i did what u told me to do:( and this gives a lot of errors)

                          Comment

                          • r035198x
                            MVP
                            • Sep 2006
                            • 13225

                            #28
                            Originally posted by tamara omar

                            i did what u told me to do:( and this gives a lot of errors)
                            No you did not. If you did, your code would be looking like this:

                            Code:
                             import javax.swing.*;
                            import javax.swing.text.*;
                            import java.awt.event.*;
                            import java.awt.Container;
                            import java.io.*;
                            import java.awt.*;
                            import java.util.ArrayList;
                            import java.util.regex.*;
                            public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                            	private Container pane;
                            	JTextArea area;
                            	JFileChooser fc;
                            	JPanel southPanel;
                            	JPanel northPanel;
                            	JPanel fieldsPanel;
                            	JPanel buttonsPanel;
                            	JScrollPane scrollPane;
                            	JTextField findText;
                            	JTextField replaceText;
                            	Matcher matcher;
                            	private String searchText = "";
                            	static private final String newline = "\n";
                            
                            	private int lastPosition = 0;
                            	public Tamara2() {
                            		pane = getContentPane(); //pane will now replace getContentPane() from now onwards
                            		setTitle("Tamara Omar");
                            		setSize(400, 400);
                            //
                            		fc = new JFileChooser();
                            		area = new JTextArea(10,20);
                            		area.setDocument(new DefaultStyledDocument());
                            		scrollPane = new JScrollPane(area);
                            
                            		area.setMargin(new Insets(5,5,5,5));
                            		area.setEditable(true);
                            
                            		//make buttons
                            		JButton clear = makeButton("Clear");
                            		JButton open = makeButton("Open");
                            		JButton save = makeButton("Save");
                            		JButton edit = makeButton("Find");
                            		JButton findAll = makeButton("Find All");
                            		JButton replaceAll = makeButton("Replace All");
                            		JButton replace = makeButton("Replace");
                            		findText = new JTextField(10);
                            		replaceText = new JTextField(10);
                            
                            
                            		southPanel = new JPanel();
                            		northPanel = new JPanel();
                            		fieldsPanel = new JPanel();
                            		buttonsPanel = new JPanel();
                            		southPanel.setLayout(new GridLayout(2, 1));
                            		//add the buttons to the panel
                            		buttonsPanel.add(findAll);
                            		buttonsPanel.add(replaceAll);
                            		buttonsPanel.add(edit);
                            		buttonsPanel.add(replace);
                            
                            		//add the fields to the panel
                            		fieldsPanel.add(new JLabel("Find:"));
                            		fieldsPanel.add(findText);
                            		fieldsPanel.add(new JLabel("Replace with:"));
                            		fieldsPanel.add(replaceText);
                            
                            
                            		//add the panel to the frame at the bottom
                            		southPanel.add(fieldsPanel);
                            		southPanel.add(buttonsPanel);
                            
                            		northPanel.add(open);
                            		northPanel.add(save);
                            		northPanel.add(clear);
                            
                            		pane.add(northPanel, "North");
                            		pane.add(scrollPane, "Center");
                            		pane.add(southPanel, "South");
                            
                            		setVisible(true);
                            }
                            public JButton makeButton(String label) { //creates a button
                            	JButton jb = new JButton(label);
                            	jb.setActionCommand(label); //This message will be set in the action for the button
                            	jb.addActionListener(this); //this (JFrame) will respond to this button's press
                            	return jb;
                            }
                            
                            public void actionPerformed(ActionEvent action) {
                            	String command = action.getActionCommand();
                            	if(command.equals("Find")) {
                            		JOptionPane.showMessageDialog(this,"Find");
                            	}
                            	else if(command.equals("Replace")) {
                            		JOptionPane.showMessageDialog(this, "Replace");
                            	}
                            	else if(command.equals("Replace All")) {
                            		String find = findText.getText();
                            		String replace = replaceText.getText();
                            		replaceAll(area, find, replace);
                            		area.requestFocus();
                            		//JOptionPane.showMessageDialog(this,"Replace All");
                            	}
                            	else if(command.equals("Find All"))	{
                            		area.setSelectedTextColor(Color.blue);
                            		area.getHighlighter().removeAllHighlights();
                            		String searchString = findText.getText();
                            		ArrayList matches = findAll(area, searchString);
                            		if(matches.size() == 0) {
                            			JOptionPane.showMessageDialog(this, searchString+" Was not found");
                            		}
                            		else {
                            			try {
                            				for(int i = 0; i < matches.size(); i++) {
                            					int x = ((Integer)matches.get(i)).intValue();
                            					//area.setCaretPosition(x);
                            					//area.moveCaretPosition(x + searchString.length());
                            					int z = x + searchString.length();
                            					area.getHighlighter().addHighlight(x, z, new DefaultHighlighter.DefaultHighlightPainter(Color.blue));
                            
                            					area.requestFocus();
                            				}
                            				JOptionPane.showMessageDialog(this, "'"+searchString+"' was found " + matches.size() + " times");
                            			}
                            			catch(Exception e) {
                            				e.printStackTrace();
                            			}
                            
                            		}
                            
                            	}
                            	else if(command.equals("Open")) {
                            		int returnVal = fc.showOpenDialog(Tamara2.this);
                            		if (returnVal == JFileChooser.APPROVE_OPTION) {
                            			 File file = fc.getSelectedFile();
                            			 BufferedReader inFile = null;
                            			 try {
                            				 inFile = new BufferedReader(new FileReader(file));
                            				 String line = "";
                            				 while ((line = inFile.readLine()) != null) {
                            					area.append(line + newline);
                            				 }
                            				 inFile.close();
                            		 	 }
                            		 	 catch(IOException iOE) {
                            			 			 	iOE.printStackTrace();
                            			 }
                            	 	 }
                            	 	 else {
                            			 area.append("Open command cancelled by user." + newline);
                            		 }
                            
                            	}
                            	else if(command.equals("Save")) {
                            		try {
                            			int returnVal = fc.showSaveDialog(Tamara2.this);
                            			if(returnVal == JFileChooser.APPROVE_OPTION) {
                            				File file = fc.getSelectedFile();
                            				BufferedWriter out = new BufferedWriter(new FileWriter(file));
                            				int rows = area.getLineCount();
                            				for(int i = 0; i < rows; i++) {
                            					int end = area.getLineEndOffset(i);
                            					int start = area.getLineStartOffset(i);
                            					int length = end - start;
                            					if(length <= 0) {
                            						length = 1;
                            					}
                            					String s = area.getText(start, (length-1));
                            					out.write(s);
                            					out.newLine();
                            					out.flush();
                            
                            				}
                            				out.close();
                            
                            
                            			}
                            			else {
                            				area.append("Save command cancelled by user." + newline);
                            			}
                            		}
                            		catch(Exception e) {
                            			e.printStackTrace();
                            		}
                            		area.setCaretPosition(area.getDocument().getLength());
                            	}
                            	if(command.equals("Clear")) {
                            		area.setText("");
                            	}
                            
                            
                            }
                            
                            //********To change to Match using regular expressions*(return vector instead of ArrayList?)*********************
                            public ArrayList findAll(JTextArea area, String text) {
                            	ArrayList startPositions = new ArrayList();
                            	int length = text.length();
                            	int rows = area.getLineCount();
                            	try {
                            		int all = area.getLineEndOffset((rows - 1));
                            		for(int i = 0; i < (all - length); i++) {
                            			String x = area.getText(i, length);
                            			if(x.equalsIgnoreCase(text)) {
                            				startPositions.add(new Integer(i));
                            			}
                            		}
                            	}
                            	catch(BadLocationException e) {
                            		e.printStackTrace();
                            	}
                            	return startPositions;
                            
                            }
                            //************Does a replace all based on regular expressions*******************
                            public void replaceAll(JTextArea area, String find, String replace) {
                            	Pattern p = Pattern.compile(find);
                            	matcher = p.matcher(area.getText());
                            	StringBuffer sb = new StringBuffer();
                            	sb.append(matcher.replaceAll(replace));
                            	area.setText(sb.toString());
                            }
                            
                            
                            
                            public static void main(String[] args) {
                            	new Tamara2();
                            	}
                            }
                            1) Replace All working and using regex
                            2)Find All working but not yet using regex package

                            Your task was to make find All work using regex package

                            Comment

                            • tamara omar
                              New Member
                              • Sep 2006
                              • 23

                              #29
                              plz im going crazy,i dont know what to do !! when i type a word and press the button find (the word disappears)!!!
                              and when i type an regular expression and press find it doesnt work
                              and when i open a word document the text area become dark and doesnt open it, i think we dont need for an open command

                              but now tell me what to do:( this is the code ,is it right till now?

                              import javax.swing.*;
                              import javax.swing.tex t.*;
                              import java.awt.event. *;
                              import java.awt.Contai ner;
                              import java.io.*;
                              import java.awt.*;
                              import java.util.Array List;
                              import java.util.regex .*;
                              public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                              private Container pane;
                              JTextArea area;
                              JFileChooser fc;
                              JPanel southPanel;
                              JPanel northPanel;
                              JPanel fieldsPanel;
                              JPanel buttonsPanel;
                              JScrollPane scrollPane;
                              JTextField findText;
                              JTextField replaceText;
                              Matcher matcher;
                              private String searchText = "";
                              static private final String newline = "\n";

                              private int lastPosition = 0;
                              public Tamara2() {
                              pane = getContentPane( ); //pane will now replace getContentPane( ) from now onwards
                              setTitle("Tamar a Omar");
                              setSize(400, 400);
                              //
                              fc = new JFileChooser();
                              area = new JTextArea(10,20 );
                              area.setDocumen t(new DefaultStyledDo cument());
                              scrollPane = new JScrollPane(are a);

                              area.setMargin( new Insets(5,5,5,5) );
                              area.setEditabl e(true);

                              //make buttons
                              JButton clear = makeButton("Cle ar");
                              JButton open = makeButton("Ope n");
                              JButton save = makeButton("Sav e");
                              JButton edit = makeButton("Fin d");
                              JButton findAll = makeButton("Fin d All");
                              JButton replaceAll = makeButton("Rep lace All");
                              JButton replace = makeButton("Rep lace");
                              findText = new JTextField(10);
                              replaceText = new JTextField(10);


                              southPanel = new JPanel();
                              northPanel = new JPanel();
                              fieldsPanel = new JPanel();
                              buttonsPanel = new JPanel();
                              southPanel.setL ayout(new GridLayout(2, 1));
                              //add the buttons to the panel
                              buttonsPanel.ad d(findAll);
                              buttonsPanel.ad d(replaceAll);
                              buttonsPanel.ad d(edit);
                              buttonsPanel.ad d(replace);

                              //add the fields to the panel
                              fieldsPanel.add (new JLabel("Find:") );
                              fieldsPanel.add (findText);
                              fieldsPanel.add (new JLabel("Replace with:"));
                              fieldsPanel.add (replaceText);


                              //add the panel to the frame at the bottom
                              southPanel.add( fieldsPanel);
                              southPanel.add( buttonsPanel);

                              northPanel.add( open);
                              northPanel.add( save);
                              northPanel.add( clear);

                              pane.add(northP anel, "North");
                              pane.add(scroll Pane, "Center");
                              pane.add(southP anel, "South");

                              setVisible(true );
                              }
                              public JButton makeButton(Stri ng label) { //creates a button
                              JButton jb = new JButton(label);
                              jb.setActionCom mand(label); //This message will be set in the action for the button
                              jb.addActionLis tener(this); //this (JFrame) will respond to this button's press
                              return jb;
                              }

                              public void actionPerformed (ActionEvent action) {
                              String command = action.getActio nCommand();
                              if(command.equa ls("Find")) {String find = findText.getTex t();
                              String replace = replaceText.get Text();
                              replaceAll(area , find, replace);
                              area.requestFoc us();
                              //JOptionPane.sho wMessageDialog( this,"find");

                              }
                              else if(command.equa ls("Replace")) {String find = findText.getTex t();
                              String replace = replaceText.get Text();
                              replaceAll(area , find, replace);
                              area.requestFoc us();
                              //JOptionPane.sho wMessageDialog( this,"Replace ");

                              }
                              else if(command.equa ls("Replace All")) {
                              String find = findText.getTex t();
                              String replace = replaceText.get Text();
                              replaceAll(area , find, replace);
                              area.requestFoc us();
                              //JOptionPane.sho wMessageDialog( this,"Replace All");
                              }
                              else if(command.equa ls("Find All")) {
                              area.setSelecte dTextColor(Colo r.blue);
                              area.getHighlig hter().removeAl lHighlights();
                              String searchString = findText.getTex t();
                              ArrayList matches = findAll(area, searchString);
                              if(matches.size () == 0) {
                              JOptionPane.sho wMessageDialog( this, searchString+" Was not found");
                              }
                              else {
                              try {
                              for(int i = 0; i < matches.size(); i++) {
                              int x = ((Integer)match es.get(i)).intV alue();
                              //area.setCaretPo sition(x);
                              //area.moveCaretP osition(x + searchString.le ngth());
                              int z = x + searchString.le ngth();
                              area.getHighlig hter().addHighl ight(x, z, new DefaultHighligh ter.DefaultHigh lightPainter(Co lor.blue));

                              area.requestFoc us();
                              }
                              JOptionPane.sho wMessageDialog( this, "'"+searchStrin g+"' was found " + matches.size() + " times");
                              }
                              catch(Exception e) {
                              e.printStackTra ce();
                              }

                              }

                              }
                              else if(command.equa ls("Open")) {
                              int returnVal = fc.showOpenDial og(Tamara2.this );
                              if (returnVal == JFileChooser.AP PROVE_OPTION) {
                              File file = fc.getSelectedF ile();
                              BufferedReader inFile = null;
                              try {
                              inFile = new BufferedReader( new FileReader(file ));
                              String line = "";
                              while ((line = inFile.readLine ()) != null) {
                              area.append(lin e + newline);
                              }
                              inFile.close();
                              }
                              catch(IOExcepti on iOE) {
                              iOE.printStackT race();
                              }
                              }
                              else {
                              area.append("Op en command cancelled by user." + newline);
                              }

                              }
                              else if(command.equa ls("Save")) {
                              try {
                              int returnVal = fc.showSaveDial og(Tamara2.this );
                              if(returnVal == JFileChooser.AP PROVE_OPTION) {
                              File file = fc.getSelectedF ile();
                              BufferedWriter out = new BufferedWriter( new FileWriter(file ));
                              int rows = area.getLineCou nt();
                              for(int i = 0; i < rows; i++) {
                              int end = area.getLineEnd Offset(i);
                              int start = area.getLineSta rtOffset(i);
                              int length = end - start;
                              if(length <= 0) {
                              length = 1;
                              }
                              String s = area.getText(st art, (length-1));
                              out.write(s);
                              out.newLine();
                              out.flush();

                              }
                              out.close();


                              }
                              else {
                              area.append("Sa ve command cancelled by user." + newline);
                              }
                              }
                              catch(Exception e) {
                              e.printStackTra ce();
                              }
                              area.setCaretPo sition(area.get Document().getL ength ());
                              }
                              if(command.equa ls("Clear")) {
                              area.setText("" );
                              }


                              }

                              //********To change to Match using regular expressions*(re turn vector instead of ArrayList?)**** *************** **
                              public ArrayList findAll(JTextAr ea area, String text) {
                              ArrayList startPositions = new ArrayList();
                              int length = text.length();
                              int rows = area.getLineCou nt();
                              try {
                              int all = area.getLineEnd Offset((rows - 1));
                              for(int i = 0; i < (all - length); i++) {
                              String x = area.getText(i, length);
                              if(x.equalsIgno reCase(text)) {
                              startPositions. add(new Integer(i));
                              }
                              }
                              }
                              catch(BadLocati onException e) {
                              e.printStackTra ce();
                              }
                              return startPositions;

                              }
                              //************Doe s a replace all based on regular expressions**** ***************
                              public void replaceAll(JTex tArea area, String find, String replace) {
                              Pattern p = Pattern.compile (find);
                              matcher = p.matcher(area. getText());
                              StringBuffer sb = new StringBuffer();
                              sb.append(match er.replaceAll(r eplace));
                              area.setText(sb .toString());
                              }



                              public static void main(String[] args) {
                              new Tamara2();
                              }
                              }

                              Comment

                              • r035198x
                                MVP
                                • Sep 2006
                                • 13225

                                #30
                                For now just restrict to opening .txt, .java, .html.(Until you get the basics of the programme working.) If we do not put the open command then we only limit the search to text that has been entered only. I included to make the program more interesting. For example you can edit your own files by replacing some words with others and saving the changes.

                                Here is how you should have done the find (notice I've changed it to find next). Perhaps now you can change the findAll to use the regular expressions. When I run on my machine, I am able to match with the patterns

                                Code:
                                import javax.swing.*;
                                import javax.swing.text.*;
                                import java.awt.event.*;
                                import java.awt.Container;
                                import java.io.*;
                                import java.awt.*;
                                import java.util.ArrayList;
                                import java.util.regex.*;
                                public class Tamara2 extends JFrame implements ActionListener { //is allowed to listen for actions
                                	private Container pane;
                                	JTextArea area;
                                	JFileChooser fc;
                                	JPanel southPanel;
                                	JPanel northPanel;
                                	JPanel fieldsPanel;
                                	JPanel buttonsPanel;
                                	JScrollPane scrollPane;
                                	JTextField findText;
                                	JTextField replaceText;
                                	Matcher matcher;
                                	Pattern pattern;
                                	private String previous = "";
                                	static private final String newline = "\n";
                                
                                	private int lastPosition = 0;
                                	public Tamara2() {
                                		pane = getContentPane(); //pane will now replace getContentPane() from now onwards
                                		setTitle("Tamara Omar");
                                		setSize(400, 400);
                                //
                                		fc = new JFileChooser();
                                		area = new JTextArea(10,20);
                                		area.setDocument(new DefaultStyledDocument());
                                		scrollPane = new JScrollPane(area);
                                
                                		area.setMargin(new Insets(5,5,5,5));
                                		area.setEditable(true);
                                
                                		//make buttons
                                		JButton clear = makeButton("Clear");
                                		JButton open = makeButton("Open");
                                		JButton save = makeButton("Save");
                                		JButton edit = makeButton("Find Next");
                                		JButton findAll = makeButton("Find All");
                                		JButton replaceAll = makeButton("Replace All");
                                		JButton replace = makeButton("Replace");
                                		findText = new JTextField(10);
                                		replaceText = new JTextField(10);
                                
                                
                                		southPanel = new JPanel();
                                		northPanel = new JPanel();
                                		fieldsPanel = new JPanel();
                                		buttonsPanel = new JPanel();
                                		southPanel.setLayout(new GridLayout(2, 1));
                                		//add the buttons to the panel
                                		buttonsPanel.add(findAll);
                                		buttonsPanel.add(replaceAll);
                                		buttonsPanel.add(edit);
                                		buttonsPanel.add(replace);
                                
                                		//add the fields to the panel
                                		fieldsPanel.add(new JLabel("Find:"));
                                		fieldsPanel.add(findText);
                                		fieldsPanel.add(new JLabel("Replace with:"));
                                		fieldsPanel.add(replaceText);
                                
                                
                                		//add the panel to the frame at the bottom
                                		southPanel.add(fieldsPanel);
                                		southPanel.add(buttonsPanel);
                                
                                		northPanel.add(open);
                                		northPanel.add(save);
                                		northPanel.add(clear);
                                
                                		pane.add(northPanel, "North");
                                		pane.add(scrollPane, "Center");
                                		pane.add(southPanel, "South");
                                
                                		setVisible(true);
                                }
                                public JButton makeButton(String label) { //creates a button
                                	JButton jb = new JButton(label);
                                	jb.setActionCommand(label); //This message will be set in the action for the button
                                	jb.addActionListener(this); //this (JFrame) will respond to this button's press
                                	return jb;
                                }
                                
                                public void actionPerformed(ActionEvent action) {
                                	String command = action.getActionCommand();
                                	if(command.equals("Find Next")) {
                                		int pos = 0;
                                		try {
                                			String s = findText.getText();
                                			if(previous.equalsIgnoreCase(s)) {
                                				pos = findNext(area, s);
                                			}
                                			else {
                                				pos = find(area, s);
                                			}
                                			if(pos == -1) {
                                				JOptionPane.showMessageDialog(this,s+" was not found");
                                			}
                                			else {
                                				int z = pos + s.length();
                                				area.getHighlighter().removeAllHighlights();
                                				area.getHighlighter().addHighlight(pos, z, new DefaultHighlighter.DefaultHighlightPainter(Color.blue));
                                			    area.requestFocus();
                                			}
                                
                                		}
                                		catch(Exception e) {
                                			e.printStackTrace();
                                		}
                                	}
                                	else if(command.equals("Replace")) {
                                		JOptionPane.showMessageDialog(this, "Replace");
                                	}
                                	else if(command.equals("Replace All")) {
                                		String find = findText.getText();
                                		String replace = replaceText.getText();
                                		replaceAll(area, find, replace);
                                		area.requestFocus();
                                		//JOptionPane.showMessageDialog(this,"Replace All");
                                	}
                                	else if(command.equals("Find All"))	{
                                		area.setSelectedTextColor(Color.blue);
                                		area.getHighlighter().removeAllHighlights();
                                		String searchString = findText.getText();
                                		ArrayList matches = findAll(area, searchString);
                                		if(matches.size() == 0) {
                                			JOptionPane.showMessageDialog(this, searchString+" Was not found");
                                		}
                                		else {
                                			try {
                                				for(int i = 0; i < matches.size(); i++) {
                                					int x = ((Integer)matches.get(i)).intValue();
                                					//area.setCaretPosition(x);
                                					//area.moveCaretPosition(x + searchString.length());
                                					int z = x + searchString.length();
                                					area.getHighlighter().addHighlight(x, z, new DefaultHighlighter.DefaultHighlightPainter(Color.blue));
                                
                                					area.requestFocus();
                                				}
                                				JOptionPane.showMessageDialog(this, "'"+searchString+"' was found " + matches.size() + " times");
                                			}
                                			catch(Exception e) {
                                				e.printStackTrace();
                                			}
                                
                                		}
                                
                                	}
                                	else if(command.equals("Open")) {
                                		int returnVal = fc.showOpenDialog(Tamara2.this);
                                		if (returnVal == JFileChooser.APPROVE_OPTION) {
                                			 File file = fc.getSelectedFile();
                                			 BufferedReader inFile = null;
                                			 try {
                                				 inFile = new BufferedReader(new FileReader(file));
                                				 String line = "";
                                				 while ((line = inFile.readLine()) != null) {
                                					area.append(line + newline);
                                				 }
                                				 inFile.close();
                                		 	 }
                                		 	 catch(IOException iOE) {
                                			 			 	iOE.printStackTrace();
                                			 }
                                	 	 }
                                	 	 else {
                                			 area.append("Open command cancelled by user." + newline);
                                		 }
                                
                                	}
                                	else if(command.equals("Save")) {
                                		try {
                                			int returnVal = fc.showSaveDialog(Tamara2.this);
                                			if(returnVal == JFileChooser.APPROVE_OPTION) {
                                				File file = fc.getSelectedFile();
                                				BufferedWriter out = new BufferedWriter(new FileWriter(file));
                                				int rows = area.getLineCount();
                                				for(int i = 0; i < rows; i++) {
                                					int end = area.getLineEndOffset(i);
                                					int start = area.getLineStartOffset(i);
                                					int length = end - start;
                                					if(length <= 0) {
                                						length = 1;
                                					}
                                					String s = area.getText(start, (length-1));
                                					out.write(s);
                                					out.newLine();
                                					out.flush();
                                
                                				}
                                				out.close();
                                
                                
                                			}
                                			else {
                                				area.append("Save command cancelled by user." + newline);
                                			}
                                		}
                                		catch(Exception e) {
                                			e.printStackTrace();
                                		}
                                		area.setCaretPosition(area.getDocument().getLength());
                                	}
                                	if(command.equals("Clear")) {
                                		area.setText("");
                                	}
                                
                                
                                }
                                
                                //********To change to Match using regular expressions*(return vector instead of ArrayList?)*********************
                                public ArrayList findAll(JTextArea area, String text) {
                                	ArrayList startPositions = new ArrayList();
                                	int length = text.length();
                                	int rows = area.getLineCount();
                                	try {
                                		int all = area.getLineEndOffset((rows - 1));
                                		for(int i = 0; i < (all - length); i++) {
                                			String x = area.getText(i, length);
                                			if(x.equalsIgnoreCase(text)) {
                                				startPositions.add(new Integer(i));
                                			}
                                		}
                                	}
                                	catch(BadLocationException e) {
                                		e.printStackTrace();
                                	}
                                	return startPositions;
                                
                                }
                                //************Does a replace all based on regular expressions*******************
                                public void replaceAll(JTextArea area, String find, String replace) {
                                	Pattern p = Pattern.compile(find);
                                	matcher = p.matcher(area.getText());
                                	StringBuffer sb = new StringBuffer();
                                	sb.append(matcher.replaceAll(replace));
                                	area.setText(sb.toString());
                                	matcher = null;
                                }
                                public int find(JTextArea area, String find) {
                                	boolean found = false;
                                	int pos = 0;
                                	pattern = Pattern.compile(find);
                                	previous = find;
                                	matcher = pattern.matcher(area.getText());
                                	found = matcher.find(0);
                                	if(!found) {
                                		pos = -1;
                                		lastPosition = 0;
                                	}
                                	else {
                                		pos = matcher.start();
                                		lastPosition = pos + find.length();
                                	}
                                	return pos;
                                }
                                
                                public int findNext(JTextArea area, String find) {
                                	boolean found = false;
                                	int pos = 0;
                                	//pattern = Pattern.compile(find);
                                	//previous = find;
                                	//matcher = pattern.matcher(area.getText());
                                	found = matcher.find(lastPosition);
                                	if(!found) {
                                		pos = -1;
                                		lastPosition = 0;
                                	}
                                	else {
                                		pos = matcher.start();
                                		lastPosition = pos + find.length();
                                	}
                                	return pos;
                                }
                                
                                
                                
                                public static void main(String[] args) {
                                	new Tamara2();
                                	}
                                }

                                Comment

                                Working...