Creating the User Interface for the Voice Help Application


Creating the User Interface for the Voice Help Application

You can use the SpeakHelp.java file to create the user interface for the Voice Help application. The user interface provides three buttons : Speak, Stop, and Help. Click the Speak button to convert the text to speech in the voice selected by an end user. Click the Stop button to stop the speech conversion. Click the Help button to listen to the help information for a menu option provided by the interface.

Listing 4-1 shows the contents of the SpeakHelp.java file:

Listing 4-1: The SpeakHelp.java File
start example
 /*Import required awt classes.*/ import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Cursor; import java.awt.Toolkit; import java.awt.Point; import java.awt.MediaTracker; import java.awt.Image; /*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.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; /*Import required swing classes.*/ import javax.swing.JOptionPane; import javax.swing.event.*; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JFrame; import javax.swing.JFileChooser; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.JToggleButton; /*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; /* Class: SpeakHelp-Creates the user interface for the textpad 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 text area of the text pad. setvoice(): Sets the voice of the synthesizer that speaks the text to the selected voice. main(): Creates the main window of the application. */ public class SpeakHelp extends JFrame implements ActionListener, Runnable, KeyListener, ItemListener {    /*Declare objects of JMenuBar class.*/    JMenuBar menubar;    /*Declare objects of JMenu class.*/    JMenu fileMenu;    JMenu voiceMenu;    /*Declare objects of JMenuItem class.*/    JMenuItem open,newFile, save,exit, selVoice, speak, pause, stop, resume;    /* Declare objects of JButton class.*/    JButton speakText, stopText;    /*Declare objects of JPanel class.*/    JPanel buttonPanel, textPanel;    /*Declare objects of JScrollPane class.*/    JScrollPane scrollpane;    /*Declare objects of JFileChooser class.*/    JFileChooser filechooser;    JTextArea textarea;    File file;    /*Declare objects of String class.*/    String str;    String speakstring;    String selectedVoice;    /*     Declare objects of FileInputStream class.    */    FileInputStream fin;    /*Declare objects of Thread class.*/    Thread t;    /*Declare objects of JToggleButton class.*/    JToggleButton togglebutton;    /*Declare objects of Cursor class.*/    Cursor cursorImage;    /*    Create an object of SelectHelpVoice class.    */    SelectHelpVoice sv=null;    /*Create an object of SpeakHelpText class.*/    SpeakHelpText st=null;    /*    SpeakHelp(): Defines the default constructor for the SpeakHelp application.    Parameters: NA    Return Value: NA    */    public SpeakHelp()    {       super("Help Application");       /*       Sets the look and feel for the textpad.       */       try       {          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");       }       catch(Exception e)       {          System.out.println("Unknown Look and Feel." + e);               }       /*Sets the size of user interface.*/       setSize(400, 400);       /*        Sets the resizable property of JFrame to false.       */       setResizable(false);       /*       Initializes the object of SelectHelpVoice class.       */       sv=new SelectHelpVoice(this);       /*       Initializes the objects of JPanels class.       */       buttonPanel=new JPanel();       textPanel=new JPanel();       /*Sets the Layout for JPanels.*/       buttonPanel.setLayout(new GridLayout(1, 3));       textPanel.setLayout(new BorderLayout());       /*       Initializes object of JMenuBar class.       */       menubar = new JMenuBar();       setJMenuBar(menubar);       /*Initializes objects of menu class.*/       fileMenu = new JMenu("File");       voiceMenu = new JMenu("Voice");       /*Adds menus to JMenuBar.*/       menubar.add(fileMenu);       menubar.add(voiceMenu);       /*        Initializes objects of JMenuItems class.       */       newFile=new JMenuItem("New (Alt+F+N)");       open = new JMenuItem("Open (Alt+F+O)");       save=new JMenuItem("Save (Alt+F+S)");       exit=new JMenuItem("Exit (Alt+F+E)");       selVoice=new JMenuItem("Select Voice (Alt+V+I)");       speak=new JMenuItem("Speak (Alt+V+P)");       stop=new JMenuItem("Stop (Alt+V+T)");       pause=new JMenuItem("Pause (Alt+V+A)");       resume=new JMenuItem("Resume (Alt+V+R)");       /*Sets Mnemonics for the JMenuItems.*/       fileMenu.setMnemonic('F');       voiceMenu.setMnemonic('V');       open.setMnemonic('O');       save.setMnemonic('S');       exit.setMnemonic('E');       selVoice.setMnemonic('I');       speak.setMnemonic('P');       stop.setMnemonic('T');       pause.setMnemonic('A');       resume.setMnemonic('R');       newFile.setMnemonic('N');       /*Adds menuitems to the file menu.*/       fileMenu.add(newFile);       fileMenu.add(open);       fileMenu.add(save);               fileMenu.addSeparator();       fileMenu.add(exit);       /*        Adds menuitems to the voice menu.       */       voiceMenu.add(selVoice);       voiceMenu.add(speak);       voiceMenu.addSeparator();       voiceMenu.add(stop);       voiceMenu.add(pause);       voiceMenu.add(resume);       /*       Adds action listener to the menuitems.       */       newFile.addActionListener(this);       open.addActionListener(this);       save.addActionListener(this);       exit.addActionListener(this);       selVoice.addActionListener(this);       speak.addActionListener(this);       stop.addActionListener(this);       pause.addActionListener(this);       resume.addActionListener(this);       save.setEnabled(false);       /*       Initializes objects of JButtons class.       */       speakText=new JButton("Speak");       stopText=new JButton("Stop");       /*        Initializes objects of JToggleButton class.       */       togglebutton=new JToggleButton("Help");       togglebutton.addItemListener(this);       /*        Sets the enables property of JButton and menu items to false.       */       stopText.setEnabled(false);       stop.setEnabled(false);       pause.setEnabled(false);       resume.setEnabled(false);       /*Add action listener to JButtons.*/       speakText.addActionListener(this);       stopText.addActionListener(this);       /*Add buttons to button panel.*/       buttonPanel.add(speakText);       buttonPanel.add(stopText);       buttonPanel.add(togglebutton);       /*        Initializes object of JTextArea class.       */       textarea=new JTextArea();       /*Set the properties of text area.*/       textarea.setLineWrap(true);       textarea.setWrapStyleWord(true);       textarea.addKeyListener(this);       /*        Initialize new JScrollpane and add text area to scroll pane.       */       scrollpane=new JScrollPane(textarea);       /*       Add button panel and scrollpane to textpanel.       */textPanel.add(scrollpane,BorderLayout.CENTER);       textPanel.add(buttonPanel,BorderLayout.NORTH);       /*       Set the default value of selected voice to kevin16.       */       selectedVoice=new String("kevin16");       /*        Add textpanel to the main window.       */       getContentPane().add(textPanel);       /*       Add new window listener to the main window.       */       addWindowListener(new WindowAdapter()       {          public void windowClosing(WindowEvent we)          {             System.exit(0);          }       });    }    /*     Handle the key typed event from the text field.     */    public void keyTyped(KeyEvent e)     {    }    /*    Handle the key pressed event from the text field.     */    public void keyPressed(KeyEvent e)     {    }    /*    Handle the key released event from the text field.     */    public void keyReleased(KeyEvent e)     {       if (e.getSource()==textarea)       {          if ((textarea.getText()).length()==0)          {             save.setEnabled(false);          }          else       {          save.setEnabled(true);       }            } } public void itemStateChanged(ItemEvent ie) {    if(ie.getStateChange()==java.awt.event.ItemEvent.SELECTED)    {       Toolkit tk = Toolkit.getDefaultToolkit();       Image icon=tk.getImage("help.gif");       MediaTracker mediaTracker = new MediaTracker(this);       mediaTracker.addImage(icon, 0);       try       {          mediaTracker.waitForID(0);       }       catch (InterruptedException ie1)       {          System.err.println(ie1);          System.exit(1);       }       Point hotPoint = new Point(1,0);       Cursor myCursor = tk.createCustomCursor(icon, hotPoint, "This is my custom Cursor");       setCursor(myCursor);     }    else    {       Cursor hourglassCursor = new Cursor(Cursor.DEFAULT_CURSOR);       setCursor(hourglassCursor);    } } /* actionPerformed(): Defines the operations to be performed, when the user clicks a button or selects a menu item. Parameters: ev: An object of ActionEvent class. Return Type: NA */ public void actionPerformed(ActionEvent ev) {    /*    Executes when the user clicks the speak button or speak menu item.    */ if((ev.getSource()==speakText)(ev.getSource()==speak))    {       /*       Set the value os selSpeak to the selected text.       */       String selSpeak=textarea.getSelectedText();       /*       Check if no text is selected.       */       if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)       {          speakstring="Speak button is used to convert written text in to speech.";       }       else       {          if(selSpeak==null)          {             speakstring=textarea.getText();             /*             Check if no text is available in the text area of the text pad.             */             if(speakstring.equals(""))             speakstring="Empty File, Please open a file and then click the Speak button";          }          else          speakstring=selSpeak;          stopText.setEnabled(true);          speakText.setEnabled(false);          pause.setEnabled(true);          resume.setEnabled(true);          stop.setEnabled(true);       }       t=new Thread(this,"Button action");       t.start();            }    else    /*    Executes when the user clicks the stop button or stop menu item.    */    if((ev.getSource()==stopText)(ev.getSource()==stop))    {       if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)       {          speakstring="Stop button is used to stop speech.";          t=new Thread(this, "Button action");          t.start();               }       else       {          /*          Invoke the closeSynthesizer() method of SpeakHelpText class          */          t.stop();          st.closeSynthesizer();          stop.setEnabled(false);          pause.setEnabled(false);          resume.setEnabled(false);          speakText.setEnabled(true);          stopText.setEnabled(false);       }    }    else    /*    Executes when the user clicks the New menu item    */    if(ev.getSource()==newFile)    {       if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)       {          speakstring="New menu item is used to open a new file.";          t=new Thread(this, "Button action");          t.start();                  return;       }       textarea.setText("");       textarea.setEditable(true);    }    else    /*    Executes when the user clicks the Open menu item    */    if(ev.getSource()==open)    {       if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)       {          speakstring="Open menu item is used to open an existing text file.";          t=new Thread(this, "Button action");          t.start();                  return;       }       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 e=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);            } } else /* Executes if the user clicks the resume menu item */ if(ev.getSource()==resume) {    if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)    {       speakstring="Resume menu item is used to resume sech after a pause.";       t=new Thread(this, "Button action");       t.start();               return;    }    /*    Invoke the resumeSynthesizer()method of the SpeakHelpText class    */    t.resume();    st.resumeSynthesizer();    stop.setEnabled(true);    stopText.setEnabled(true);    pause.set Enabled(true); } else /* Executes if the user clicks the pause button */ if(ev.getSource()==pause) {    if (getCursorType()!=java.awt.Cursor.D EFAULT_CURSOR)    {       speakstring="Pause menu item is used to pause speech.";       t=new Thread(this, "Button action");       t.start();               return;    }    /*    Invoke the pauseSynthesizer() method of the SpeakHelp Text class    */    t.suspend();    .pauseSynthesizer();    resume.setEnabled(true); } else /* Executes if the user clicks the exit button */ if(ev.getSource()==exit) {    System.out.println(getCursorType());    System.out.println();    if (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)    {       speakstring="Stop button is used to stop speech.";       t=new Thread(this, "Button action");       t.start();               return;    }    System.exit(0); } else /* Executes if the user clicks the Select voice menu item. */ if(ev.getSource()==selVoice) {    if  (getCursorType()!=java.awt.Cursor.DEFAULT_CURSOR)    {       speakstring="Select Voice menu item is used to select a voice.";       t=new Thread(this, "Button action");       t.start();               return;    }    sv.setVisible(true); } else /* Executes if the user clicks the save menu item. */ if(ev.getSource()==save) {    if (getCursorType()!=java.awt.Cursor.D EFAULT_CURSOR)    {       speakstring="Save menu item is used to save the text in a text file.";       t=new Thread(this, "Button action");       t.start();               return;    }    if(textarea.getText().equals(""))    JOptionPane.showMessageDialog(null, "No file open or empty    file.","Warning", JOptionPane.WARNING_MESSAGE);    else    {       /* Displays the save dialog box */       if       (filechooser.showSaveDialog(SpeakHelp.this) == JFileChooser.APPROVE_OPTION)       {          File fSelected = filechooser.getSelectedFile();          try          {             FileWriter out = new FileWriter(fSelected);             textarea.write(out);             out.close();          }           catch(IOException ioe)           {             ioe.printStackTrace();          }                                       }    }                         } } public void run() {    /*    Initialize a new object of SpeakHelpText class.    */    st=new SpeakHelpText(speakstring,selectedVoice);    /*    Invoke the speakSelText() method of SpeakHelpText class.    */    st.speakSelText(this);    /*    Enable the stop button, pause, and resume menu items.    */ } /* Executes if the user clicks the Open menu item. */ 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) {    selectedVoice=str;    System.out.println(selectedVoice); } /* main(): Creates an object of SpeakHelp.java class. Parameters: str[]: String array to store the command line parameters. Return Type: NA */ public static void main(String str[]) {    SpeakHelp tp=new SpeakHelp();    tp.setVisible(true); } } 
end example
 

Download this listing .

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

The various methods defined in Listing 4-1 are:

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

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

  • setvoice (): Sets the voice of the synthesizer. The application uses this voice to read out the help information for the menu options and buttons provided in the interface.

The SpeakHelp.java file generates the main window of the Voice Help application, as shown in Figure 4-2:

click to expand: this figure shows the user interface of the voice help application, which contains the file and voice menus and the speak, stop, and help buttons.
Figure 4-2: User Interface of the Voice Help Application

Figure 4-3 shows the options of the File menu:

click to expand: this figure shows the options that are available in the file menu of the voice help application.
Figure 4-3: The File Menu

Figure 4-4 shows the various options of the Voice menu:

click to expand: this figure shows the options available in the voice menu of the voice help application.
Figure 4-4: The Voice Menu



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