Creating the User Interface for the Counting Application


Creating the User Interface for the Counting Application

The SpeechCounting.java file creates the user interface for the Counting application. Listing 5-1 shows the contents of the SpeechCounting.java file:

Listing 5-1: The SpeechCounting.java File
start example
 import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Toolkit; /*Import required awt event classes.*/ import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /*Import required io classes.*/ import java.io.File; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.FileWriter; import javax.swing.text.BadLocationException; import java.util.StringTokenizer; /* Class: SpeechCounting-Creates the user interface for the SpeechCounting Methods: actionPerformed(): Defines the actions to be performed, when user clicks any button or menu item. open(): Opens the file selected by the end user in the textarea of the textpad. main(): Creates the main window of the application. */ public class SpeechCounting extends JFrame implements ActionListener {    /*Declare objects of JMenuBar class.*/    JMenuBar menubar;    /* Declare objects of JMenu class.*/    JMenu filemenu;    /*Declare objects of JMenuItem class.*/    JMenuItem openfilemenuitem,selectvoicemenuitem,exitmenuitem;    /* Declare objects of JTextArea class.*/    JTextArea textarea;    /*Declare objects of JScrollPane class.*/    JScrollPane scrollpane;    /*Declare objects of JPanel class.*/    JPanel buttonpanel;    /*Declare objects of JButton class.*/    JButton vowelcounterbutton, Consonantcounterbutton, wordcounterbutton, sentencecounterbutton;    /*Declare objects of String class.*/    String textareastring;    String selectedvoicename;    String speakstring;    String str;    /*Declare objects of JFileChooser class.*/    JFileChooser filechooser;    /*Declare objects of File class.*/    File file;    /*Declare objects of FileInputStream class.*/    FileInputStream fin;    /*Declare objects of SpeakCounting class.*/    SpeakCounting st;    /*Declare objects of SelectVoiceType class.*/    SelectVoiceType selectvoice;    public SpeechCounting()    {       /*Sets the window title.*/       super("Vowel, Consonant, Word, and Sentence Counting Application");       /*        Sets the look and feel for the speechcounting.       */       try       {                  UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");       }       catch(Exception e)       {          System.out.println("Unknown Look and Feel."+e);          }       /*        Declare and initialize object of Container class.        */       Container contentpane=getContentPane();       /*Initialize object of String class.*/       textareastring=new String();       /*        Initialize object of JMenuItems class.       */       openfilemenuitem = new JMenuItem("Open (Alt+F+O)");       selectvoicemenuitem=new JMenuItem("Select Voice (Alt+F+V)");       exitmenuitem=new JMenuItem("Exit (Alt+F+E)");       /*        Declare and initialize object of Dimension class.       */       Dimension screendimension=Toolkit.getDefaultToolkit().getScreenSize();       /*Sets window location.*/       setLocation(screendimension.width/2-250,screendimension.height/2-250);       /*Sets action command for menu items.*/       openfilemenuitem.setActionCommand("open");       selectvoicemenuitem.setActionCommand("voice");       exitmenuitem.setActionCommand("exit");       /*Sets mnemonic for items.*/       openfilemenuitem.setMnemonic('O');       selectvoicemenuitem.setMnemonic('V');       exitmenuitem.setMnemonic('E');       /*Adds action listener for items.*/       openfilemenuitem.addActionListener(this);       selectvoicemenuitem.addActionListener(this);       exitmenuitem.addActionListener(this);       /*Initialize object of JMenu class.*/       filemenu=new JMenu("File");       /*Sets mnemonic for menu.*/       filemenu.setMnemonic('F');       /*Sets window closing operation.*/       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       /*Adds menu items to menu.*/       filemenu.add(openfilemenuitem);       filemenu.add(selectvoicemenuitem);       filemenu.add(exitmenuitem);       /*       Initialize object of JMenuBar class.        */       menubar=new JMenuBar();       /*Adds menus to menu bar.*/       menubar.add(filemenu);       setJMenuBar(menubar);       vowelcounterbutton=new JButton("Vowel");       Consonantcounterbutton=new JButton("Consonant");       wordcounterbutton=new JButton("Word");       sentencecounterbutton=new JButton("Sentence");       /*        Sets action command for menu buttons.        */       vowelcounterbutton.setActionCommand("vowel");       Consonantcounterbutton.setActionCommand("consonant");       wordcounterbutton.setActionCommand("word");       sentencecounterbutton.setActionCommand("sentence");       /*Sets mnemonic for buttons.*/       vowelcounterbutton.setMnemonic('V');       Consonantcounterbutton.setMnemonic('C');       wordcounterbutton.setMnemonic('W');       sentencecounterbutton.setMnemonic('S');       /*Adds action listener for buttons.*/       vowelcounterbutton.addActionListener(this);       Consonantcounterbutton.addActionListener(this);       wordcounterbutton.addActionListener(this);       sentencecounterbutton.addActionListener(this);       /*        Initialize object of JPanel and sets layout as gridlayout.       */       buttonpanel=new JPanel(new GridLayout(1, 4, 5, 5));       /*Adds buttons to panel.*/       buttonpanel.add(vowelcounterbutton);       buttonpanel.add(Consonantcounterbutton);       buttonpanel.add(wordcounterbutton);       buttonpanel.add(sentencecounterbutton);       /*Adds panel to contentpane.*/       contentpane.add(buttonpanel, BorderLayout.NORTH);       /*       Initialize object of JTextArea class.        */       textarea=new JTextArea();       /*        Initialize object of JScrollPane class.       */       scrollpane=new JScrollPane(textarea);       /*Adds panel to contentpane.*/       contentpane.add(scrollpane);       /*       Initialize object of SelectVoiceType class.       */       selectvoice=new SelectVoiceType(this);       /*       Initialize object of String class.       */       selectedvoicename=new String("kevin16");       selectvoice.getOkButton().addActionListener(new ActionListener()       {          public void actionPerformed(ActionEvent ae)          {             selectedvoicename=selectvoice.getVoiceName();             selectvoice.setVisible(false);          }       });       /*Set the size of user interface.*/       setSize(400,400);       /*Set the visibility true.*/       setVisible(true);    }    /*    actionPerformed - This method is called when the user clicks the Vowel, Consonant,     Word or Sentence    button, selects file menu items.    Parameters: ae - an ActionEvent object containing details of the event.    Return Value: NA    */    public void actionPerformed(ActionEvent ae)    {       String actioncommand=ae.getActionCommand();       /*       This is executed when user clicks the Open menu item.       */       if (actioncommand=="open")       {          try          {                /*Initialize a new JFileChooser.*/             filechooser=new JFileChooser();             /*             Create and set a new FileFilter for the JFileChooser.             */             filechooser.setFileFilter(new javax.swing.filechooser.FileFilter()             {             public boolean accept(File f)             {                if(f.isDirectory())                {                   return true;                }                String name=f.getName();                /*                Allows only text and java files to be opened in the user interface of text pad.                */                if ((name.endsWith(".txt"))(name.endsWith(".java")))                {                   return true;                }                return false;             }             public String getDescription()             {                return "Text Files";             }          });          /*Open the JFileChooser.*/          filechooser.showOpenDialog(this);          file = filechooser.getSelectedFile();          if(file==null)          {             System.out.println("No file Selected");          }          else          {             /*              Check if the selected file is a valid file.             */             if(file.isFile())             {                str = file.getAbsolutePath();                open();             }             else             {                /*                 Print the error message if the selected file is not a valid file.                */                JOptionPane.showMessageDialog(null,"The selected file is not a valid File","Select                 another File",JOptionPane.WARNING_MESSAGE);             }          }       }       catch(Exception e)        {          System.out.println("Error" + e);          }    }    /*    This is executed when user clicks the Voice menu item.    */    if(actioncommand=="voice")    selectvoice.setVisible(true);    /*    This is executed when user clicks the Exit menu item.    */    if(actioncommand=="exit")    System.exit(0);    /*    This is executed when user clicks the Vowel button.    */    if(actioncommand=="vowel")    {       /*Declare objects of String class.*/       String textareachar;       textareastring = textarea.getText();       int textarealength=textareastring.length();       int vowelcount=0;       for(int i=0;i<textarealength;i++)       {          textareachar=textareastring.substring(i,i+1);          if("aeiou".indexOf(textareachar)!=-1)          {             vowelcount=vowelcount+1;          }       }       if(vowelcount==1)       {          speakstring="There is "+vowelcount +"Vowel.";       }       else       {          speakstring="There are "+vowelcount +"Vowels.";       }       st=new SpeakCounting(speakstring,selectedvoicename);       /*       Invoke the speakSelText() method of SpeakCounting class       */       st.speakSelText();    }    /*    This is executed when user clicks the Consonant button.    */    if (actioncommand=="consonant")    {       String textareachar;       textareastring = textarea.getText();       int textarealength=textareastring.length();       int consonantcount=0;       for(int i=0;i<textarealength;i++)       {          textareachar=textareastring.substring(i,i+1);          if ("bcdfghjklmnopqrstuwxyz".indexOf(textareachar)!=-1)          {             consonantcount=consonantcount+1;          }       }       if(consonantcount==1)       {          speakstring="There is "+consonantcount +"Consonant.";       }       else       {          speakstring="There are "+consonantcount +"Consonants.";       }       st=new SpeakCounting(speakstring,selectedvoicename);       /*       Invoke the speakSelText() method of SpeakCounting class       */       st.speakSelText();    }    /*    This is executed when user clicks the Word button.    */    if(actioncommand=="word")    {       textareastring = textarea.getText();       int totalLines = textarea.getLineCount();       int wordlength=0;       for (int i=0;i< totalLines;i++ )       {          try          {             int start = textarea.getLineStartOffset(i);             int end = textarea.getLineEndOffset(i);             String line = textareastring.substring(start, end);             String[] words=line.split(" ");             for(int j=0;j<words.length;j++ )             {                if(words[j].trim().length()>0)                {                   wordlength=wordlength+1;                }             }          }          catch(BadLocationException ble)          {          }       }       if(wordlength==1)       {          speakstring="There is "+wordlength +"Word.";       }       else       {          speakstring="There are "+wordlength +"Words.";       }       st=new SpeakCounting(speakstring,selectedvoicename);       /*       Invoke the speakSelText() method of SpeakCounting class.       */       st.speakSelText();    }    /*    This is executed when user clicks the Sentence button.    */    if(actioncommand=="sentence")    {       textareastring = textarea.getText();       StringTokenizer sttoken = new StringTokenizer(textareastring,".");       int lengthofarray=sttoken.countTokens();       if(lengthofarray==1)       {          speakstring="There is"+lengthofarray+"Sentence.";       }       else       {          speakstring="There are "+lengthofarray +"Sentences.";       }       st=new SpeakCounting(speakstring,selectedvoicename);       /*       Invoke the speakSelText() method of SpeakCounting class.       */       st.speakSelText();       }    }    /*    open: This method opens a file dialog box.    Parameter: NA    Return Value: NA    */    public void open()     {       try       {          /*          Initialize a new FileInputStream.          */          fin = new FileInputStream(filechooser.getSelectedFile().getAbsolutePath());          /*          Initialize a new object of BufferedReader class.          */          BufferedReader br = new BufferedReader(new InputStreamReader(fin));          String readLine = "";          textarea.setText("");          while ((readLine = br.readLine())!=null)          {             textarea.setText(textarea.getText()+ "\n"+readLine);          }          if(textarea.getText()==null)          {             JOptionPane.showMessageDialog(null, "The file has no content", "Select another             File", JOptionPane.WARNING_MESSAGE);          }          fin.close();       }       catch(IOException ioe)       {          System.err.println("I/O Error on Open");       }    }    /*    setvoice(): retrieves the voice selected by the end user.    Parameters:    str:String representing the voice selected by the end user    Return Type: NA    */    public void setvoice(String str)    {       selectedvoicename=str;    }    public static void main(String[] args)     {       SpeechCounting speechcounting=new SpeechCounting();    } } 
end example
 

Download this listing .

In the above code, the main() method creates an instance of the SpeechCounting.java class.

The methods defined in Listing 5-1 are:

  • actionPerformed(): Acts as an event listener and activates an appropriate method based on the action the end user performs .

  • open(): Opens the file selected by the end user in the text area provided by the interface.

  • main(): Creates the main window of the application.

The SpeechCounting.java file creates the main window of the Counting application, as shown in Figure 5-2:

click to expand: this figure shows the user interface of the counting application, which contains the file menu and four buttons.
Figure 5-2: User Interface of the Counting Application

Figure 5-3 shows the File menu options of the Counting application:

click to expand: this figure shows the options available in the file menu of the counting application.
Figure 5-3: The File Menu of the Counting Application

To open an existing text file, select File->Open. The Open dialog box appears, as shown in Figure 5-4:

click to expand: this figure shows the dialog box to open a text file in the text area provided by the user interface.
Figure 5-4: The Open Dialog Box

Select the required file and click Open to open a file.

Select File-> Select Voice to select the voice in which the Counting application reads out the count values of vowels, consonants, words, and sentences in the text specified by an end user.

Click File-> Exit to close the Counting application.




Java InstantCode. Developing Applications using Java Speech API
Java InstantCode. Developing Applications using Java Speech API
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 46

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net