Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Other Java > Java GUI
Password Reminder
Register
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
Java GUI Discussions specific to programming Java GUI.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Java GUI section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old October 26th, 2004, 03:48 PM
Authorized User
 
Join Date: Aug 2004
Location: toronto, ontario, Canada.
Posts: 13
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Star007
Default spell checker

HI there,
I am working a spell checker GUI program and I am kinda stuck on search for a word and replacing.
I imported a file with all the words.

the fuctions of the programs is as follows
as i type in the text area if there is a misspelled which is smilar to the one from the imported file then it should highlight or underline and then when i go to tools and check for spelling ti should suggest similar words and i should be able to replace or ignore the word or ignore all...
well to sum up i need a spell check just like in ms word

here is my code...
plz help me out...



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.FileFilter;
import java.util.*;
import javax.swing.text.html.*;
import javax.swing.border.*;
import javax.swing.text.DefaultCaret;

public class spellchecker
{
  public static void main(String[] args)
  {
     // use Win32 look and feel

     try {
        UIManager.setLookAndFeel(
           UIManager.getSystemLookAndFeelClassName());
     } catch (Exception e) {}

     String fileName = null;
     if (args.length == 1)
     {
        if (args[0].equals("?") || args[0].equals("/?") ||
args[0].equals("-?"))
        {
           System.out.println("usage: java DemoFileMenu [file]\n\n" +
              "where file = a file to open, view, and edit");
           System.exit(0);
        } else
           fileName = args[0];
     }

     a2Frame frame = new a2Frame(fileName);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
     frame.setTitle("DemoFileMenu");
     frame.pack();
     frame.show();
  }
}

class a2Frame extends JFrame implements ActionListener, KeyListener
{
  final String TITLE = "Assingment #2";

  JMenuItem newFile;
  JMenuItem open;
  JMenuItem close;
  JMenuItem save;
  JMenuItem saveAs;
  JMenuItem exit;
  JMenuItem find;
  JMenuItem replace;

  File f;

  TreeMap dict;

  JFileChooser fc;
  JFileChooser flk;
  JScrollPane sp;
  JEditorPane editArea;
  JEditorPane tempJEP;

  JPanel blank;

  boolean dataChanged; // keep track of whether changes have been made

  public a2Frame(String fileName)
  {
     // -------------------------------
     // create and configure components
     // -------------------------------

     // create a text area to view and edit the file

     try{
       TreeMap dict = new TreeMap();
       BufferedReader bb = new BufferedReader(new FileReader("tmpdict.txt"));
       String s = bb.readLine();
       StringTokenizer st = new StringTokenizer(s, " ");
       for (String g = st.nextToken(); st.hasMoreTokens(); g = st.nextToken())
       {
               dict.put(g,null);
       }

       System.out.println(dict.containsKey("abasgkgkge")) ;
     }
     catch(Exception e){
     System.out.println(e);
       popupError("Can't open dictionary file");
       }



     editArea = new JEditorPane();
     editArea.setText("");
     editArea.setFont(new Font("monospaced", Font.PLAIN, 12));
     sp = new JScrollPane();
     sp.setPreferredSize(new Dimension(600, 400));

     // create a blank panel to put in the scrollpane when no file is open

     blank = new JPanel();
     blank.setOpaque(true);
     blank.setBackground(Color.gray);
     sp.setViewportView(blank);

     // build the File menu

     JMenuBar mb = new JMenuBar();
     this.setJMenuBar(mb);

     JMenu fileMenu = new JMenu("File");
     fileMenu.setMnemonic(KeyEvent.VK_F);
     mb.add(fileMenu);

     newFile = new JMenuItem("New...", new ImageIcon("new.gif"));
     newFile.setMnemonic(KeyEvent.VK_N);
     newFile.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_N, ActionEvent.CTRL_MASK));

     open = new JMenuItem("Open...", new ImageIcon("open.gif"));
     open.setMnemonic(KeyEvent.VK_O);
     open.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_O, ActionEvent.CTRL_MASK));

     close = new JMenuItem("Close");
     close.setMnemonic(KeyEvent.VK_C);
     close.setEnabled(false);

     save = new JMenuItem("Save");
     save.setMnemonic(KeyEvent.VK_S);
     save.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_S, ActionEvent.CTRL_MASK));
     save.setEnabled(false);

     saveAs = new JMenuItem("Save as...");
     saveAs.setMnemonic(KeyEvent.VK_A);
     saveAs.setEnabled(false);

     exit = new JMenuItem("Exit");
     exit.setMnemonic(KeyEvent.VK_X);

     fileMenu.add(newFile);
     fileMenu.add(open);
     fileMenu.add(close);
     fileMenu.addSeparator();
     fileMenu.add(save);
     fileMenu.add(saveAs);
     fileMenu.addSeparator();
     fileMenu.add(exit);

     JMenu toolMenu = new JMenu("Tools");
     fileMenu.setMnemonic(KeyEvent.VK_T);
     mb.add(toolMenu);

     find = new JMenuItem("Find");
     find.setMnemonic(KeyEvent.VK_F);
     find.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_F, ActionEvent.CTRL_MASK));
     find.setEnabled(false);

     replace = new JMenuItem("Replace");
     replace.setMnemonic(KeyEvent.VK_R);
     replace.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_R, ActionEvent.CTRL_MASK));
       replace.setEnabled(false);

     toolMenu.add(find);
     toolMenu.add(replace);

     // set up a file chooser to present *.txt and *.java files
     // in the current directory

     fc = new JFileChooser(new File("."));
     final String[] EXTENSIONS = { ".txt", ".java" };
     fc.addChoosableFileFilter(new MyFileFilter(EXTENSIONS));

     // -------------
     // add listeners
     // -------------

     newFile.addActionListener(this);
     open.addActionListener(this);
     close.addActionListener(this);
     save.addActionListener(this);
     saveAs.addActionListener(this);
     exit.addActionListener(this);
         find.addActionListener(this);
         replace.addActionListener(this);

     // Note: a KeyListener will be added whenever new editing begins.
     // The 'dataChanged' flag will be set in the actionPerformed
     // method with the first keystroke, and then the KeyListener will
     // be removed. The next time new editing begins, the KeyListener
     // will be added again, and so on.

     // put components in a panel

     JPanel p = new JPanel(new BorderLayout());
     p.add(sp, "Center");

     // make panel this JFrame's content pane

     this.setContentPane(p);

     // open the file specified on the command line, if any

     if (fileName != null)
     {
        f = new File(fileName);
        openFile(f);
     }
  }

  // -------------------------------
  // implement ActionListener method
  // -------------------------------

  public void actionPerformed(ActionEvent ae)
  {
     Object source = ae.getSource();

     if (source == newFile)
     {
        editArea.setText("");
        editArea.addKeyListener(this);
        dataChanged = false;
        this.setTitle("untitiled - " + TITLE);
        sp.setViewportView(editArea);
        editArea.requestFocus();
        editArea.setCaretPosition(0);
        close.setEnabled(true);
        save.setEnabled(true);
        saveAs.setEnabled(true);
        find.setEnabled(true);
        replace.setEnabled(true);
     }

     else if (source == open)
     {
        // show the file chooser 'open' dialog box and get user response

        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
        {
           f = fc.getSelectedFile();
           openFile(f);
        }
     }

     else if (source == save)
     {
        // If the edit area was loaded from a file, save the changes.
        // If the edit area was loaded from the "New..." menu item,
        // get a filename from the user before saving. To do this,
        // just invoke 'doClick' on the "Save as..." component. This
        // will fire an ActionEvent, and the filename will be retrieved
        // from the corresponding code in the actionPerformed method;
        // that is, in the code corresponding to "source == saveAs".

        if (f != null)
           saveToFile(f);
        else
           saveAs.doClick();
     }

     else if (source == saveAs)
     {
        // show the file chooser 'save' dialog box and get user response

        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        {
           f = fc.getSelectedFile();

           // check if file exists before overwriting
           // (Note: Dialog only pops up if file exists)

           if (!f.exists() || okToReplace(f))
              saveToFile(f);
        }
     }

     else if (source == close)
     {
        if (dataChanged && changesShouldBeSaved())
           if (f != null)
              saveToFile(f);
           else
              saveAs.doClick();

        f = null;
        this.setTitle(TITLE);
        editArea.setText("");
        close.setEnabled(false);
        save.setEnabled(false);
        saveAs.setEnabled(false);
        find.setEnabled(false);
        replace.setEnabled(false);
        sp.setViewportView(blank);
     }
         else if (source == find)
     {
                 CustomFindDialog cfd = new CustomFindDialog(this);
                 cfd.show();

         }
         else if (source == replace){
               CustomReplaceDialog crd = new CustomReplaceDialog(this);
               crd.show();
       }

     else if (source == exit)
        System.exit(0);
  }

  private boolean okToReplace(File f)
  {
     final Object[] options = { "Yes", "No", "Cancel" };
     return JOptionPane.showOptionDialog(this,
                 "The file '" + f.getName() +
                 "' already exists. " +
                 "Replace existing file?",
                 "Warning",
                 JOptionPane.YES_NO_CANCEL_OPTION,
                 JOptionPane.WARNING_MESSAGE,
                 null,
                 options,
                 options[2]) == JOptionPane.YES_OPTION;
  }

  private boolean changesShouldBeSaved()
  {
     final Object[] options = { "Yes", "No", "Cancel" };
     return JOptionPane.showOptionDialog(this,
                 "Save changes before closing?",
                 "Close",
                 JOptionPane.YES_NO_CANCEL_OPTION,
                 JOptionPane.QUESTION_MESSAGE,
                 null,
                 options,
                 options[2]) == JOptionPane.YES_OPTION;
  }

  // -----------------------------
  // implement KeyListener methods
  // -----------------------------

  public void keyPressed(KeyEvent ke) {

  }

  public void keyReleased(KeyEvent ke) {}

  // The following is only needed for the first editing keystroke.
  // Set the 'dataChanged' flag and then remove the KeyListener.
  // This avoids an endless stream of calls to the keyTyped
  // method during editing.

  public void keyTyped(KeyEvent ke)
  {
     dataChanged = true;
  }

  // -------------
  // other methods
  // -------------

  private void openFile(File fArg)
  {
     try
     {
        editArea.read(new FileInputStream(fArg), null);
     } catch (IOException e)
     {
        popupError("Error reading file '" + fArg.getName() + "'!");
        return;
     }

     editArea.setCaretPosition(0);
     dataChanged = false;
     sp.setViewportView(editArea);

     this.setTitle(fArg.getName() + " - " + TITLE);
     close.setEnabled(true);
         find.setEnabled(true);
         replace.setEnabled(true);
     save.setEnabled(true);
     saveAs.setEnabled(true);
     return;
  }

  private void popupError(String s)
  {
     //Toolkit.getDefaultToolkit().beep();
               System.out.print("\07");
               System.out.flush();
     JOptionPane.showMessageDialog(this, s, "Error",
        JOptionPane.ERROR_MESSAGE);
     return;
  }

  private void saveToFile(File fArg)
  {
     PrintWriter pw = null;

     try
     {
        pw = new PrintWriter(new BufferedWriter(new FileWriter(fArg)));
     } catch (IOException e)
     {
        popupError("Can't open file '" + fArg.getName() + "' for writing");
        return;
     }

     pw.print(editArea.getText());
     pw.close();
     this.setTitle(fArg.getName() + " - " + TITLE);
     dataChanged = false;
     editArea.addKeyListener(this);
  }

  // -------------
  // inner classes
  // -------------
  class CustomFindDialog extends JDialog implements ActionListener,
KeyListener
  {
          private JButton close;
          private JButton findB;
          private JButton findAgain;
          private JCheckBox caseSen;

          private String s;
          private String tmp;
          private int position;
          private int totalPos = 0;
          private int countEnter = 0;
          private DefaultCaret ca;

          private TextField findWord;
          CustomFindDialog(Frame owner){
               super(owner,"Find String",true);
               this.setResizable(false);
               this.setDefaultCloseOperation(WindowConstants.DO_N OTHING_ON_CLOSE);
               close = new JButton("Close");
               findB = new JButton("Find");
               findAgain = new JButton("Find again");
               findAgain.setEnabled(false);

               JPanel pane = new JPanel();
               pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
               findWord = new TextField("",30);

               JPanel buttons = new JPanel();
               buttons.add(findB);
               buttons.add(findAgain);
               buttons.add(close);

               JPanel checkBoxes = new JPanel();
               caseSen = new JCheckBox("Case Sensitive");
               checkBoxes.add(caseSen);

               pane.add(findWord);
               pane.add(checkBoxes);
               pane.add(buttons);

               this.setContentPane(pane);
               this.pack();

               findWord.addKeyListener(this);
               caseSen.addActionListener(this);
               close.addActionListener(this);
               findB.addActionListener(this);
               findAgain.addActionListener(this);
          }
          public void actionPerformed(ActionEvent ae){
                 if(ae.getSource() == findB){
                       s = editArea.getText();
                       tmp = findWord.getText();
                       if (!caseSen.isSelected()){
                               s = s.toLowerCase();
                               tmp = tmp.toLowerCase();
                               countEnter = 0;
                       }
                       position = s.indexOf(tmp);
                       if (position == -1){

                               //display nomatch
                       }
                       else{

                               ca = (DefaultCaret)editArea.getCaret();
                               ca.setDot(position);
                               ca.moveDot(position + (findWord.getText()).length());
                       }

                       findAgain.setEnabled(true);
                       totalPos = 0;
                 }
                 else if(ae.getSource() == findAgain)
                 {
                       position = editArea.getCaretPosition();
                       s = s.substring(position - totalPos);
                       countEnter = 0;
                       totalPos = position;
                       System.out.println(s);
                       position = s.indexOf(tmp);
                       if (position == -1){
                               s = editArea.getText();
                               tmp = findWord.getText();
                               totalPos = 0;
                               if (!caseSen.isSelected()){
                                       s = s.toLowerCase();
                                       tmp = tmp.toLowerCase();
                               }
                               countEnter = 0;
                               findB.doClick();
                       }
                       else
                       {
                       System.out.println(position+ " " + totalPos);

                       ca.setDot(totalPos + position);
                       ca.moveDot(totalPos + position + (findWord.getText()).length());
                       }
               }

               else if(ae.getSource() == caseSen){
                       findAgain.setEnabled(false);
               }

                 else if(ae.getSource() == close){

                         this.hide();
                 }
          }

          public void keyPressed(KeyEvent ke) {
               findAgain.setEnabled(false);

               }

          public void keyReleased(KeyEvent ke) {
               if(ke.getKeyCode() == KeyEvent.VK_ENTER){
                       findB.doClick();
               }

       }

          public void keyTyped(KeyEvent ke)
          {
          }
  }

  class CustomReplaceDialog extends JDialog implements ActionListener,
KeyListener
  {
          private JButton close;
          private JButton replaceB;
          private JButton replaceAll;
          private JButton findB;
          private JCheckBox caseSen;

          private String s = "";
          private String tmp;
          private int position;
          private int totalPos = 0;
          private int countEnter = 0;
          private DefaultCaret ca;

          private TextField replaceWord;
          private TextField findWord;

          CustomReplaceDialog(Frame owner){
               super(owner,"replace String",true);
               this.setResizable(false);
               this.setDefaultCloseOperation(WindowConstants.DO_N OTHING_ON_CLOSE);
               close = new JButton("Close");
               replaceB = new JButton("Replace");
               replaceAll = new JButton("Replace all");
               findB = new JButton("Find");
               replaceB.setEnabled(false);

               JPanel pane = new JPanel();
               pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
               replaceWord = new TextField("",30);
               findWord = new TextField("",30);

               JPanel buttons = new JPanel();
               buttons.add(findB);
               buttons.add(replaceB);
               buttons.add(replaceAll);
               buttons.add(close);

               JPanel checkBoxes = new JPanel();
               caseSen = new JCheckBox("Case Sensitive");
               checkBoxes.add(caseSen);

               JPanel findPanel = new JPanel();
              findPanel.setBorder(new TitledBorder(new EtchedBorder(), "String to find"));
               findPanel.add(findWord);

               JPanel replacePanel = new JPanel();
               replacePanel.setBorder(new TitledBorder(new EtchedBorder(), "String to change"));
               replacePanel.add(replaceWord);

               pane.add(findPanel);
               pane.add(replacePanel);
               pane.add(checkBoxes);
               pane.add(buttons);

               this.setContentPane(pane);
               this.pack();

               findWord.addKeyListener(this);
               caseSen.addActionListener(this);
               findB.addActionListener(this);
               close.addActionListener(this);
               replaceB.addActionListener(this);
               replaceAll.addActionListener(this);

          }
          public void actionPerformed(ActionEvent ae){
                 if(ae.getSource() == findB){
                         if(s.length() == 0){
                                 tmp = findWord.getText();

                                       s = editArea.getText();

                                       if (!caseSen.isSelected()){
                                               s = s.toLowerCase();
                                               tmp = tmp.toLowerCase();
                                       }
                                        countEnter = 0;

                         }
                         else{
                                 System.out.println("here");
                                 position = editArea.getCaretPosition();
                               s = s.substring(position - totalPos + countEnter);
                               totalPos = position;
                         }
                         position = s.indexOf(tmp);

                       System.out.println(s);
                       System.out.println(totalPos + " " + position);

                       if (position == -1){
                               s = editArea.getText();
                               tmp = replaceWord.getText();
                               totalPos = 0;
                               if (!caseSen.isSelected()){
                                       s = s.toLowerCase();
                                       tmp = tmp.toLowerCase();
                               }
                               //display nomatch
                               totalPos = 0;
                               s = "";

                       }
                       else{

                               ca = (DefaultCaret)editArea.getCaret();

                               ca.setDot(totalPos + position);
                               ca.moveDot(totalPos + position + (findWord.getText()).length());
                       }

                       replaceB.setEnabled(true);

                 }
                 else if(ae.getSource() == replaceB)
                 {
                         /*String original = editArea.getText();
                         position = editArea.getCaretPosition();
                         original = original.substring(0,position -
(findWord.getText()).length()) + replaceWord.getText() +
original.substring(totalPos);
                         editArea.setText(original);
                         String findEnter = s.substring(0,position);
                               for (int i = 0;i < findEnter.length() ; i++ )
                               {
                                       if (findEnter.charAt(i) == '\n')
                                       {
                                               countEnter ++;
                                       }
                               }
                               ca.setDot(position - (findWord.getText()).length());
                         ca.moveDot(position - (findWord.getText()).length() +
(replaceWord.getText()).length());
                         s = s.substring(position - totalPos + countEnter);
                         totalPos = totalPos + position + countEnter;

                         System.out.println(s);
                         System.out.println(totalPos + " " + position + " "+
countEnter);
                               */
                               int replaceInt = editArea.getCaretPosition();
                               String original = editArea.getText();
                               System.out.println("----------------------");
                               //original = original.substring(0, totalPos + position) +
//replaceWord.getText() + original.substring(totalPos + position + 3);

                               //editArea.setText(original);
                               int o = totalPos + position;
                               System.out.println(original.substring(0, o + countEnter));

                               System.out.println(original.substring(o + 3 + countEnter));
                               System.out.println("----------------------");
                               ca.setDot(replaceInt - (findWord.getText()).length());
                               ca.moveDot(replaceInt);
                               System.out.println(s);
                               System.out.println(totalPos + " " + position + " "+
countEnter);

                 }
                 else if(ae.getSource() == replaceAll)
                  {
                         System.out.println("all");
                         String original = editArea.getText();

                         for (int i = original.indexOf(findWord.getText()) ;i != -1 ;i =
original.indexOf(findWord.getText()) )
                         {
                                 original = original.substring(0,i) + replaceWord.getText() +
original.substring(i + (findWord.getText()).length());
                         }

                         editArea.setText(original);
                  }

               else if(ae.getSource() == caseSen){
                       replaceB.setEnabled(false);
               }

                 else if(ae.getSource() == close){

                         this.hide();
                 }
          }

          public void keyPressed(KeyEvent ke) {
                       s = "";
                       replaceB.setEnabled(false);

               }

          public void keyReleased(KeyEvent ke) {
               if(ke.getKeyCode() == KeyEvent.VK_ENTER){
                       replaceB.doClick();
               }

       }

          public void keyTyped(KeyEvent ke)
          {
          }
  }
  /** A class to extend the FileFilter class
  * (which is abstract) and implement the 'accept' and
  * 'getDescription' methods.
  */
  class MyFileFilter extends FileFilter
  {
     private String[] s;

     MyFileFilter(String[] sArg)
     {
        s = sArg;
     }

     // determine which files to display in the chooser
     public boolean accept(File fArg)
     {
        // if it's a directory, show it
        if (fArg.isDirectory())
        return true;

        // if the filename contains the extension, show it
        for (int i = 0; i < s.length; ++i)
           if (fArg.getName().toLowerCase().indexOf(s[i].toLowerCase())
> 0)
__________________
***************
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need help with Spell checker in GUI Star007 Java GUI 0 October 26th, 2004 03:46 PM
Spell checker srotondo Access 3 October 22nd, 2004 10:53 PM
Spell Checker srotondo Classic ASP Basics 3 October 6th, 2004 08:07 PM
Spell Checker zaeem Classic ASP Basics 3 November 10th, 2003 11:01 AM
Spell Checker Lucy Classic ASP Professional 1 November 3rd, 2003 02:42 PM



All times are GMT -4. The time now is 08:33 AM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.