Creating the User Interface for the Speech-Enabled Calendar Application


Creating the User Interface for the Speech-Enabled Calendar Application

You can use the SpeechCalendar.java file to create a user interface that contains separate tabs for specifying the date, day, and time. You can click the Date tab to retrieve the current date, select the required date format, and insert the required date to convert to speech. You can click the Day and Time tabs to open and retrieve the current day and time values from the computer and allow the end user to specify the required day and time values. The user interface contains the Speak button, which allows the end user to convert the specified date, day, or time values to speech.

Listing 2-1 shows the contents of the SpeechCalendar.java file:

Listing 2-1: The SpeechCalendar.java File
start example
 /*Import required packages*/ import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JOptionPane; import java.util.*; import javax.swing.event.*; import java.text.DateFormat; /* Class: SpeechCalendar-Creates the user interface for the speech-enabled calendar. Methods: calculateDay(): Retrieves the current day from the system calendar. calculateDate(): Retrieves the current date from the system calendar. calculateTime(): Retrieves the current time from the system clock. actionPerformed(): Defines the actions to be performed when user clicks the buttons in  the user interface. getMntName(): Returns the string value of the month that is passed as a parameter. dateIsValid(): Validates the date entered by the user. getYear(): Returns the string value for the year. main(): Creates an object of SpeechCalendar class. setFormat(): Sets the date in the format specified by the user. */ public class SpeechCalendar extends JFrame implements ActionListener {    /*Declare variables*/    Calendar c;    String format;    String dayValue, dateValue, timeValue, speak, k1, k2, k3;    JTabbedPane pane;    JPanel mainPanel;    JPanel datePanel, dayPanel, timePanel;    ButtonGroup dayBg, dateBg, timeBg;    JRadioButton cDate, selDate, cDay, selDay, cTime, selTime;    JLabel appTitle;    JButton dateSpeak,daySpeak, timeSpeak, dateCancel, dayCancel, timeCancel, selFormat;    JTextField date, day,time, dateText, dayText, timeText;    String dayString, dateString, timeString;    SelectFormat sf = null;    Font f,f1;    /*    SpeechCalendar(): Default constructor of SpeechCalendar class.    Parameters:NA    Return Type:NA    */    public SpeechCalendar()    {       /*Set the look and feel for the application*/       try       {          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");       }       catch(Exception e)       {          System.out.println("Unknown Look and Feel." + e);             }       /*Initialize object of SelectFormat class*/       sf = new SelectFormat(this);       sf.setSize(250,250);       sf.setResizable(false);       /*Create an instance of Calendar class*/       Calendar c=Calendar.getInstance();       /*Create objects of Font class*/       f=new Font("Verdana",Font.BOLD,12);       f1=new Font("Verdana",Font.BOLD,10);       /*Initialize main panel*/       appTitle=new JLabel("Speech-Enabled Calendar");       appTitle.setFont(f);       mainPanel=new JPanel();       /*Initialize contents of JTabbedPane*/       pane=new JTabbedPane();       datePanel=new JPanel();       dayPanel=new JPanel();       timePanel=new JPanel();       /*Add tabs to JTabbedPane*/       pane.addTab("Date",datePanel);       pane.addTab("Day",dayPanel);       pane.addTab("Time",timePanel);       /*Create button groups*/       dateBg=new ButtonGroup();       dayBg=new ButtonGroup();       timeBg=new ButtonGroup();       /*Initialize JRadioButtons*/       cDate=new JRadioButton("Current Date",true);       cDay=new JRadioButton("Current Day",true);       cTime=new JRadioButton("Current Time",true);       selDate=new JRadioButton("Enter Date (dd/mm/yyyy)",false);       selDay=new JRadioButton("Enter Day",false);       selTime=new JRadioButton("Enter Time (hh:mm:ss)",false);       /*Set font of JRadioButtons*/       cDate.setFont(f1);       cDay.setFont(f1);       cTime.setFont(f1);       selDate.setFont(f1);       selDay.setFont(f1);       selTime.setFont(f1);       /*Add JRadioButtons to ButtonGroup*/       dateBg.add(cDate);       dateBg.add(selDate);       dayBg.add(cDay);       dayBg.add(selDay);       timeBg.add(cTime);       timeBg.add(selTime);       /*Initialize JTextFields*/       dateText=new JTextField(15);       dayText=new JTextField(15);       timeText=new JTextField(15);       date=new JTextField(15);       day=new JTextField(15);       time=new JTextField(15);       /*Initialize JButtons*/       dateSpeak=new JButton("Speak");       daySpeak=new JButton("Speak");       timeSpeak=new JButton("Speak");       dateCancel=new JButton("Exit");       dayCancel=new JButton("Exit");       timeCancel=new JButton("Exit");       selFormat=new JButton("Select Date Format");       /*Set Font of buttons*/       dateSpeak.setFont(f1);       daySpeak.setFont(f1);       timeSpeak.setFont(f1);       dateCancel.setFont(f1);       dayCancel.setFont(f1);       timeCancel.setFont(f1);       selFormat.setFont(f1);       /*Add action listeners to the JButtons*/       dateSpeak.addActionListener(this);       daySpeak.addActionListener(this);       timeSpeak.addActionListener(this);       dateCancel.addActionListener(this);       dayCancel.addActionListener(this);       timeCancel.addActionListener(this);       selFormat.addActionListener(this);       /*Set the contents of datePanel*/       datePanel.setLayout(new GridLayout(4, 2));       datePanel.add(cDate);       datePanel.add(date);       datePanel.add(selDate);       datePanel.add(dateText);       datePanel.add(selFormat);       JLabel tmp=new JLabel("");       datePanel.add(tmp);       datePanel.add(dateSpeak);       datePanel.add(dateCancel);       /*Set contents of day panel*/       dayPanel.setLayout(new GridLayout(3, 2));       dayPanel.add(cDay);       dayPanel.add(day);       dayPanel.add(selDay);       dayPanel.add(dayText);       dayPanel.add(daySpeak);       dayPanel.add(dayCancel);       /*Set contents of time panel*/       timePanel.setLayout(new GridLayout(3, 2));       timePanel.add(cTime);       timePanel.add(time);       timePanel.add(selTime);       timePanel.add(timeText);       timePanel.add(timeSpeak);       timePanel.add(timeCancel);       /*Set contents of mainPanel*/             mainPanel.add(appTitle);       mainPanel.add(pane);       /*Initialize the main window*/       setSize(400,200);       setResizable(false);       /*Add mainPanel to the current window*/       getContentPane().add(mainPanel);       /*       Call CalculateDay() method to retrieve the current day       */       dayValue=CalculateDay(c);       /*        Call CalculateDate() method to retrieve the current date       */       dateValue=CalculateDate(c);       /*        Call CalculateTime() method to retrieve the current time       */       timeValue=CalculateTime(c);       /*       Set current date value in the date textfield       */       date.setText(dateValue);       /*       Set current day value in the day textfield       */       day.setText(dayValue);       /*       Set current time value in the time textfield       */       time.setText(timeValue);       /*       Disable the text fields displaying the current date, day, and time       */       date.setEnabled(false);       day.setEnabled(false);       time.setEnabled(false);       format="dd/mm/yyyy";    }    /*    CalculateDay(): Retrieves the value of current day from the system calendar.     parameters:    c: An object of Calendar class.    Return Type:String    */    public String CalculateDay(Calendar c)     {       /*Get the current value of day*/       int day = c.get(Calendar.DAY_OF_WEEK);       String day1 = null;       /*        Convert the current day to its string value       */       if(day==1)        day1 = "Sunday";       else if(day==2)        day1 = "Monday";       else if(day==3)        day1 = "Tuesday";       else if(day==4)        day1 = "Wednesday";       else if(day==5)        day1 = "Thursday";       else if(day==6)        day1 = "Friday";       else if(day==7)        day1 = "Saturday";       /*Return current day*/       return day1;    }    /*    CalculateDate(): Returns the current date    Parameters:    c: An object of Calendar class.    Return Type: String    */    public String CalculateDate(Calendar c)    {       /*Get the current date*/       int date=c.get(Calendar.DAY_OF_MONTH);       /*Get the current month*/       int mnt=c.get(Calendar.MONTH);       /*Get the current year*/       int year=c.get(Calendar.YEAR);       String date1;       /*       Convert the current date, month, and year to the corresponding string values       */       k1=String.valueOf(year);       if(mnt<10)       {          String val="0";          k2=val+String.valueOf(mnt+1);       }       k3=String.valueOf(date);       date1=k3+"/"+k2+"/"+k1;       /* Return current date*/       return date1;    }    /*    CalculateTime(): Returns the value of current time from the system calendar.    Parameters:    c: An object of Calendar class.    Return Type: String.    */    public String CalculateTime(Calendar c)    {       /*Get the value of present hour*/       int hour=c.get(Calendar.HOUR);       /*Get the value of present minutes*/       int minute=c.get(Calendar.MINUTE);       /*Get the value of present seconds*/       int second=c.get(Calendar.SECOND);       int a_p=c.get(Calendar.AM_PM);        /*       Convert the present hour, minutes, and seconds to string       */       String hr,min,sec;       String tempTime="0";       String timeTot="12:00:00 AM";       if(hour<9)       hr=tempTime+String.valueOf(hour);       else       hr=String.valueOf(hour);                   if(minute<10)       min=tempTime+String.valueOf(minute);       else       min=String.valueOf(minute);       if(second<10)       sec=tempTime+String.valueOf(second);       else       sec=String.valueOf(second);       if (a_p==0)       {          timeTot=hr+":"+min+":"+sec+" AM";       }       else       {          timeTot=hr+":"+min+":"+sec+" PM";       }       /*Return the present time*/       return timeTot;    }    /*     actionPerformed(): Defines the operation to be performed when the user clicks a button.    Parameters:    ev: An object of ActionEvent.    Return Type: NA    */    public void actionPerformed(ActionEvent ev)    {       /*       This part of the code executes if the end user clicks the Cancel button in any pane of the       JTabbedPane       */       if((ev.getSource()==dateCancel)(ev.getSource()==dayCancel)(ev.getSource()==timeCancel))       {          System.exit(0);       }       else       /*       This part of code executes if the user clicks the Select date format button       */       if(ev.getSource()==selFormat)       {          sf.setVisible(true);       }       else        {                /*           This part of code executes when the user clicks the Speak button in the Day pane of the          JTabbedPane          */          if(ev.getSource()==daySpeak)          {          speak="No entry specified";          /*          Checks if the JRadioButton Current Day is selected          */          if(cDay.isSelected())          {             speak=dayValue;          }          else          /*           Checks if the JRadioButton, Enter Date is selected          */          if(selDay.isSelected())          {             if((dayText.getText().compareToIgnoreCase("Monday")!=0)&&             (dayText.getText().compareToIgnoreCase("Tuesday")!=0)&&             (dayText.getText().compareToIgnoreCase("Wednesday")!=0)&&             (dayText.getText().compareToIgnoreCase("Thursday")!=0)&&             (dayText.getText().compareToIgnoreCase("Friday")!=0)&&             (dayText.getText().compareToIgnoreCase("Saturday")!=0)&&             (dayText.getText().compareToIgnoreCase("Sunday")!=0))             {                /* Prompts that the day entered is wrong*/                speak="You have entered an invalid entry for day, Enter again";                dayText.setText("");                dayText.grabFocus();             }             else             /*Speaks the day entered by the user*/             speak=dayText.getText();          }        }       /*       This part of code executes when the user clicks the Speak button in the Date pane       */       else if(ev.getSource()==dateSpeak)       {          speak="No entry specified";          /*Checks if the JRadioButton, Current Date is selected*/          if(cDate.isSelected())          {             /*Initialize an object of StringTokenizer class*/             StringTokenizer st=new StringTokenizer(date.getText(),"/");             /*Checks if there exists any tokens in the StringTokenizer class*/             while(st.hasMoreTokens())             {                format=selDate.getLabel().substring(12,22);                String val1=st.nextToken();                String val2=st.nextToken();                String val3=st.nextToken();                String temp;                /*Checks if the selected format is yyyy/mm/dd or yy/mm/dd*/                if (format.equals("yyyy/mm/dd")format.equals("yy/mm/dd"))                {                   temp=getYear(Integer.parseInt(val1));                   speak=temp+" "+getMntName(val2)+" "+val3;                   System.out.println(speak);                }                else                /*Checks if the selected format is mm/dd/yy or mm/dd/yyyy*/                if(format.equals("mm/dd/yy")format.equals("mm/dd/yyyy"))                {                   temp=getYear(Integer.parseInt(val3));                   speak=getMntName(val1)+" "+val2+" "+temp;                   System.out.println(speak);                }                else                /*Checks if the selected format is dd/mm/yy or dd/mm/yyyy*/                if(format.equals("dd/mm/yy")format.equals("dd/mm/yyyy"))                {                   temp=getYear(Integer.parseInt(val3));                   speak=val1+" "+getMntName(val2)+" "+temp;                   System.out.println(speak);                }             }          }                      else          /*           Checks if the JRadioButton, Enter Date is selected                */          if(selDate.isSelected())          {             /*             Create an instance of StringTokenizer class             */             StringTokenizer st=new StringTokenizer(dateText.getText(),"/");             /*             Get the count of total number of tokens in the StringTokenizer class             */             int count=st.countTokens();             /*             Checks if the value of count is 3             */             if(count==3)             {                /*                Checks and executes if the StringTokenizer class contains any token                */                while(st.hasMoreTokens())                {                /*                Retrieve the tokens in String variables.                */                String chk1=st.nextToken();                String chk2=st.nextToken();                String chk3=st.nextToken();                String tmp;                /*                Convert the string values of tokens to integers                */                int i=Integer.parseInt(chk1);                int j=Integer.parseInt(chk2);                int k=Integer.parseInt(chk3);                /*                Checks if the selected format is yyyy/mm/dd or yy/mm/dd                */                if (format.equals("yyyy/mm/dd")format.equals("yy/mm/dd"))                {                   /*                   Checks if the date entered is valid or not.                   */                   boolean res=dateIsValid(i, j, k);                   if(res)                   {                      tmp=getYear(i);                      speak=tmp+" "+getMntName(chk2)+""+chk3;                   }                   else                   {                      /*                      Prompts that an invalid date is entered                      */                      speak="Invalid date, please try again";                      dateText.setText("");                      dateText.grabFocus();                   }                }                else                /*                Checks if the selected format is mm/dd/yy or mm/dd/yyyy                */                if(format.equals("mm/dd/yy")format.equals("mm/dd/yyyy"))                {                   /*                   Checks for a valid date                   */                   boolean res=dateIsValid(k, i, j);                   if(res)                   {                      tmp=getYear(k);                      speak=getMntName(chk1)+""+chk2+""+tmp;                   }                   else                   {                      /*                                        Prompts for an invalid date entry                      */                      speak="Invalid date, please try again";                      dateText.setText("");                      dateText.grabFocus();                   }                }                else                /*                Checks if the selected date format is dd/mm/yy or dd/mm/yyyy                */                if(format.equals("dd/mm/yy")format.equals("dd/mm/yyyy"))                {                   /*                   Checks if a date is valid                   */                   boolean res=dateIsValid(k,j,i);                   if(res)                   {                      tmp=getYear(k);                      speak=chk1+" "+getMntName(chk2)+" "+tmp;                   }                   else                   {                      /*                      Prompts that the date entered is invalid                      */                      speak="Invalid date, please try again";                      dateText.setText("");                      dateText.grabFocus();                   }                }             }          }          else          {             /*             Prompts for an invalid date entry format             */             speak="Invalid date format, enter again";             /*             Clear the dateText text field             */             dateText.setText("");             /*             Set the focus to the dateText textfield             */             dateText.grabFocus();          }       }    }    /*    This code executes when the user clicks the Speak button in the Time pane of JTabbedPane    */    else if(ev.getSource()==timeSpeak)    {       speak="no entry specified";       /*       Checks if the JRadioButton, Current Time is selected       */       if(cTime.isSelected())       {          /*          Create an object of StringTokenizer class          */          StringTokenizer st=new StringTokenizer(time.getText(),":");          /*          Checks if the StringTokenizer class has any element          */          while(st.hasMoreTokens())          {             speak="The time is"+st.nextToken()+"hours"+st.nextToken()+"minutes"+st.nextToken()+"             seconds";          }       }       else       /*       Checks if the JRadioButton, Enter Time is selected       */       if(selTime.isSelected())       {          /*          Create an object of StringTokenizer class          */          StringTokenizer st=new StringTokenizer(timeText.getText(),":");          /*          Count the number of tokens in the StringTokenizer class          */          int count=st.countTokens();          /*          Checks if three tokens exists          */          if (count==3)          {             /*              Executes if the STringTokenizer class contains any token             */             while (st.hasMoreTokens())             {                /*                Convert the values of current hour, current minutes, and current seconds to integer                values                */                int hr=Integer.parseInt(st.nextToken());                int min=Integer.parseInt(st.nextToken());                int sec=Integer.parseInt(st.nextToken());                /*                checks if the time specified is valid                */                if(hr>=0 && hr<=24 && min>=0 && min<60 &&                sec>=0 && sec<60)                speak=" The time is"+String.valueOf(hr)+"hour"+String.valueOf(min)                +"minutes"+String.valueOf(sec)+"seconds";                else                {                         /*                   Prompt for invalid entry of time                   */                   speak=" The time specified is invalid, please enter again";                   /*                   clear the text field to enter time                   */                   timeText.setText("");                   /*                   Set the focus to the cleared text field                   */                   timeText.grabFocus();                }             }          }          else          {             /*             Prompts that the entry for time is invalid             */             speak="Invalid format for time, enter again";             timeText.setText("");             timeText.grabFocus();          }       }    }    /*    create and initializes an instance of SpeakText class.    */    SpeakText hw=new SpeakText(speak); } } /* setFormat():Select the date format Parameters:  s: An object of String class Return Type:NA */ public void setFormat(String s) {    format=s;    System.out.println(format);    StringTokenizer dateToken=new StringTokenizer(dateValue,"/");    /*    Checks if the selected date format is yyyy/mm/dd    */    if (s.equals("yyyy/mm/dd"))    {       selDate.setLabel("Enter Date (yyyy/mm/dd)");       date.setText(k1+"/"+k2+"/"+k3);    }    else    /*    Checks if the selected date format is yy/mm/dd    */           if(s.equals("yy/mm/dd"))    {       selDate.setLabel("Enter Date (yy/mm/dd)");       date.setText(k1.substring(2,4)+"/"+k2+"/"+k3);    }    else    /*    Checks if the selected date format is mm/dd/yy    */    if(s.equals("mm/dd/yy"))    {       selDate.setLabel("Enter Date (mm/dd/yy)");       date.setText(k2+"/"+k3+"/"+k1.substring(2,4));    }    else    /*    Checks if the selected date format is mm/dd/yyyy    */    if(s.equals("mm/dd/yyyy"))    {       selDate.setLabel("Enter Date (mm/dd/yyyy)");       date.setText(k2+"/"+k3+"/"+k1);    }    else    /*    Checks if the selected date format is dd/mm/yy    */    if(s.equals("dd/mm/yy"))    {       selDate.setLabel("Enter Date (dd/mm/yy)");       date.setText(k3+"/"+k2+"/"+k1.substring(2,4));    }    else    /*    Checks if the selected date format is dd/mm/yyyy    */    if(s.equals("dd/mm/yyyy"))    {       selDate.setLabel("Enter Date (dd/mm/yyyy)");       date.setText(k3+"/"+k2+"/"+k1);    }    dateText.setText("");    dateText.grabFocus(); } /* getMntName(): Retrieves the string value of the month passed as a parameter to the method Parameters: mnt: An object of String class. Return Type: String */ public String getMntName(String mnt) {    String month=null;    /*    Retrieves the corresponding string value of the month    */    if(mnt.equals("1")mnt.equals("01")) month = "January";    else if(mnt.equals("2")mnt.equals("02")) month = "February";    else if(mnt.equals("3")mnt.equals("03")) month = "March";    else if(mnt.equals("4")mnt.equals("04")) month = "April";    else if(mnt.equals("5")mnt.equals("05")) month = "May";    else if(mnt.equals("6")mnt.equals("06")) month = "June";    else if(mnt.equals("7")mnt.equals("07")) month = "July";    else if(mnt.equals("8")mnt.equals("08")) month = "August";    else if(mnt.equals("9")mnt.equals("09")) month = "September";    else     if(mnt.equals("10")) month = "October";    else     if(mnt.equals("11")) month = "November";    else     if(mnt.equals("12")) month = "December";    /*Return month*/    return month; } /* dateIsValid():Checks if a date is valid Parameters: year: Integer value for the year. month: Integer value for the month. day: Integer value for the day. Return Type: boolean */ private static boolean dateIsValid(int year, int month, int day) {    boolean result = true;    try    {                   /*        Create an object of DateFormat class       */       DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);       df.setLenient(false);       final String dateString = month + "/" + day + "/" + year;       df.parse(dateString);    }    catch (Exception e)    {       result = false;    }    /*    Return the boolean variable, result    */    return result; } /* getYear(): Returns the current year. Parameters: a: Integer value for the year. Return Type: String */ public String getYear(int a) {    String yearSpeak;    if(a>=80 && a<=99)    {       yearSpeak="Nineteen"+String.valueOf(a);    }    else    if (a>=01 && a<=04)    {       yearSpeak="Two thousand"+String.valueOf(a);    }    else    yearSpeak=String.valueOf(a);    return yearSpeak; } /*  main(): Creates the main window for the application Parameters str[]: An array of String values. Return Type: NA */ public static void main(String str[]) {    /*     Initialize an instance of SpeechCalendar class    */    SpeechCalendar sc=new SpeechCalendar();    sc.setVisible(true); } } 
end example
 

Download this listing .

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

The SpeechCalendar.java class generates the user interface of the Speech-Enabled Calendar application, as shown in Figure 2-2:

click to expand: this figure shows the user interface and the date tab of the speech-enabled calendar application. this user interface contains three tabs: date, day, and time.
Figure 2-2: User Interface of the Speech-Enabled Calendar Application

In Listing 2-1, the actionPerformed() method is defined. This method acts as an event listener and activates an appropriate method, based on the button selected by the end user. The argument in the actionPerformed() method specifies the action to be performed. For example, when an end user selects the Current Date option on the Date tab, the actionPerformed() method invokes the CalculateDate() method, which retrieves the current date from the computer. When an end user selects the Enter Date option on the Date tab, the actionPerformed() method invokes the getText() method, which allows the end user to specify a date and invokes the dateIsValid() method. The dateIsValid() method validates the date entered by the end user.

After the end user enters the required date and clicks the Speak button, the SpeechCalendar.java file calls the Speaktext.java file. The SpeakText.java file invokes the speakPlainText() method, which converts the specified date to speech.

The application terminates if the end user clicks the Exit button.

The methods defined in Listing 2-1 are:

  • actionPerformed(): Acts as an event listener and activates an appropriate method, based on the option selected by the end user. This method is invoked when an end user clicks the options in the Date tab.

  • dateIsValid(): Validates the date specified by the end user.




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