Creating the User Interface


The PortModem.java file creates the user interface of the Modem Dialer application. Listing 3-1 shows the content of the PortModem.java file:

Listing 3-1: The PortModem.java File

start example
 /*Imports required Comm package classes.*/ import javax.comm.*; /*Imports required I/O package classes.*/ import java.io.*; /*Imports required java.swing package classes.*/ import javax.swing.*; import javax.swing.event.*; /*Imports required AWT classes.*/ import java.awt.*; import java.awt.event.*; /* class PortModem - This class is the main class of the application.  This class initializes the interface and loads all components like the button,  textfields before displaying the result. Constructor:    PortModem-This constructor creates GUI. Methods:    expect - Get response from modem     send - send commands to modem main - This method creates the main window of the application and displays all the components. */ public class PortModem extends JFrame implements ActionListener {    /*Declare objects of JButton class.*/    private JButton dialbutton;    private JButton cancelbutton;    private JButton closebutton;    private JButton portbrowsebutton;    /*Declare objects of JPanel class.*/    private JPanel bottompanellower;    private JPanel bottompanelupper;    private JPanel middlepanel;    private JPanel bottompanel;    /*Declare objects of JLabel class.*/    private JLabel applicationtitlelabel;    private JLabel portnamelabel;    private JLabel phonenumberlabel;    private JLabel processlabel;    /*Declare objects of JTextField class.*/    private JTextField portnametextbox;    private JTextField phonenumbertextbox;    /*Declare constraints.*/    private final int BUTTON_WIDTH=80;    private final int BUTTON_HEIGHT=23;    private final int TEXTBOX_WIDTH=150;    public static final int BAUD = 9600;    protected boolean start = true;    /*Declare object of DataInputStream class.*/    protected DataInputStream is;    /*Declare object of PrintStream class.*/    protected PrintStream os;    String response;    /*     Declare and initialize object of CommPortIdentifier class.    */    CommPortIdentifier commportid=null;    /*     Declare and initialize object of CommPort class.    */    CommPort commport=null;    /*Declare object of PortChooser class.*/    PortChooser portchooser;    public PortModem() throws IOException, NoSuchPortException,PortInUseException,UnsupportedCommOperationException     {       /*Set parent window title.*/       super("Modem Dialer Application");       /*        Initialize and set the Look and Feel of the application to Windows Look and Feel.       */       try       {                      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());       }        catch(Exception e)       {          System.out.println("Unable to set WLF"+e);       }       /*Override windowClosing method.*/       addWindowListener(new WindowAdapter()       {          public void windowClosing(WindowEvent we)          {             System.exit(0);          }       });       /*       Declare and initialize object of Container class.       */       Container contentpane=getContentPane();          /*Set background color to white.*/       contentpane.setBackground(Color.white);       /*       Declare and initialize object of Dimension class.       */       Dimension  screendimension=Toolkit.getDefaultToolkit().getScreenSize();       /*Set window's location on screen.*/       setLocation(screendimension.width/2- 200,screendimension.height/2-200);       /*Initialize object of JLabel.*/       applicationtitlelabel=new JLabel("Phone Call Application",JLabel.CENTER);       /*Set label font.*/       applicationtitlelabel.setFont(new Font("Verdana",Font.BOLD,14));       /*Add label to contentpane.*/       contentpane.add(applicationtitlelabel,BorderLayout.NORTH);       /*Initialize object of JButton.*/       dialbutton=new JButton("Dial");       /*Set button size.*/       dialbutton.setPreferredSize(new Dimension(BUTTON_WIDTH,BUTTON_HEIGHT));       /*Add action command to button.*/       dialbutton.setActionCommand("dial");       /*Add action listener to button.*/       dialbutton.addActionListener(this);       /*Set mnemonic for button .*/       dialbutton.setMnemonic('D');       dialbutton.setToolTipText("Click this button for dialing.");       /*Initialize object of JButton.*/       cancelbutton=new JButton("Cancel");       cancelbutton.setPreferredSize(new Dimension(BUTTON_WIDTH,BUTTON_HEIGHT));       /*Add action command to button.*/       cancelbutton.setEnabled(false);       cancelbutton.setActionCommand("cancel");       /*Add action listener to button.*/       cancelbutton.addActionListener(this);       /*Set mnemonic for button.*/       cancelbutton.setMnemonic('C');       /*Set tool tip text.*/       cancelbutton.setToolTipText("Click this button for cancel dialing.");       /*Initialize object of Jbutton.*/       closebutton=new JButton("Close");       /*Set button size.*/       closebutton.setPreferredSize(new Dimension(BUTTON_WIDTH,BUTTON_HEIGHT));       /*Add action command to button.*/       closebutton.setActionCommand("close");       /*Add action listener to button.*/       closebutton.addActionListener(this);       /*Set mnemonic for button.*/       closebutton.setMnemonic('l');       /*Add tooltip text with button.*/       closebutton.setToolTipText("Click this button to close this window.");       /*Initialize object of JPanel.*/       bottompanellower=new JPanel();       /*Add buttons to panel.*/       bottompanellower.add(dialbutton);       bottompanellower.add(cancelbutton);       bottompanellower.add(closebutton);       /*Initialize object of JPanel.*/       bottompanelupper=new JPanel();       /*Initialize object of JLabel.*/       processlabel=new JLabel("Disconnected");       processlabel.setForeground(Color.blue);       /*Add label to panel.*/       bottompanelupper.add(processlabel);       /*       Initialize object of JPanel and set the layout as GridLayout.       */       bottompanel=new JPanel(new GridLayout(2,1));       /*Add panels to bottompanel.*/       bottompanel.add(bottompanelupper);       bottompanel.add(bottompanellower);       /*Add bottompanel pane to contentpane.*/       contentpane.add(bottompanel,BorderLayout.SOUTH);       /*       Declare and initialize object of GridBagLayout.       */       GridBagLayout gridlayout=new GridBagLayout();       /*       Declare and initialize object of GridBagConstraints.       */       GridBagConstraints gridbagconstraints =new GridBagConstraints();       /*       Initialize object of JPanel class and set layout as GridBagLayout.       */       middlepanel=new JPanel(gridlayout);       /*initialize object of JLabel.*/       portnamelabel=new JLabel("Port Name",JLabel.LEFT) ;       /*Set constraints for portnamelabel.*/       gridbagconstraints.fill=GridBagConstraints.HORIZONTAL;       gridbagconstraints.anchor=GridBagConstraints.CENTER;       gridbagconstraints.gridx=0;       gridbagconstraints.gridy=0;       gridlayout.setConstraints(portnamelabel,gridbagconstraints);       /*Add label to pane.*/       middlepanel.add(portnamelabel);       /*Initialize object of JtextField.*/       portnametextbox=new JTextField();       /*Set button size.*/       portnametextbox.setPreferredSize(new Dimension(TEXTBOX_WIDTH,BUTTON_HEIGHT));       /*Set constraints for portnametextbox.*/       gridbagconstraints.gridx=1;       gridbagconstraints.gridy=0;       portnametextbox.setEnabled(false);       gridlayout.setConstraints(portnametextbox,gridbagconstraints);       /*Add label to pane.*/       middlepanel.add(portnametextbox);       /*Initialize object of JButton.*/       portbrowsebutton=new JButton("Browse..");       /*Add action listener to button.*/       portbrowsebutton.addActionListener(this);       /*Add action command to button.*/       portbrowsebutton.setActionCommand("portbrowse");       /*Set button size.*/       portbrowsebutton.setPreferredSize(new Dimension(BUTTON_WIDTH,BUTTON_HEIGHT));       /*Set constraints for portbrowsebutton.*/       gridbagconstraints.gridx=2;       gridbagconstraints.gridy=0;       gridlayout.setConstraints(portbrowsebutton,gridbagconstraints);       middlepanel.add(portbrowsebutton);          /*       Initialize object of JLabel and set its title.       */       phonenumberlabel=new JLabel("Phone Number",JLabel.LEFT);       /*Set constraints for phonenumberlabel.*/       gridbagconstraints.gridx=0;       gridbagconstraints.gridy=1;       gridbagconstraints.insets=new Insets(5,0,0,0);       gridlayout.setConstraints(phonenumberlabel,gridbagconstraints);       middlepanel.add(phonenumberlabel);       /*Initialize object of JTextField.*/       phonenumbertextbox=new JTextField();       /*Set textbox size.*/       phonenumbertextbox.setPreferredSize(new Dimension(TEXTBOX_WIDTH,BUTTON_HEIGHT));       /*       Set constraints for phonenumbertextbox.       */       gridbagconstraints.gridx=1;       gridbagconstraints.gridy=1;       gridlayout.setConstraints(phonenumbertextbox,gridbagconstraints);       middlepanel.add(phonenumbertextbox);       contentpane.add(middlepanel,BorderLayout.CENTER);       /*       Initialize object as PortChooser class.       */       portchooser=new PortChooser(this);       /*       Add action listener to ok button of portchooser object.       */       portchooser.getOkButton().addActionListener(new ActionListener()       {          public void actionPerformed(ActionEvent e)           {             portchooser.dispose();             if (portchooser.getSelectedName()==null||portchooser.getSelectedName()=="")             {             System.out.println("Select the port");             }             else             {                portnametextbox.setText(portchooser.getSelectedName());             }          }       });       /*Set window size.*/       setSize(400,300);       /*Make it visible.*/       setVisible(true);       }       /*       actionPerformed - This method is called when the user clicks the Dial, cancel, close button.       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 Close button.          */          if("close".equals(actioncommand))          {             System.exit(0);          }          /*          This is executed when user clicks the Browse button.          */          if("portbrowse".equals(actioncommand))          {             portchooser.setVisible(true);          }          /*          This is executed when user clicks the Cancel button.          */          if ("cancel".equals(actioncommand))          {             try             {                /*close input and output stream.*/                is.close();                os.close();                /*Port close.*/                commport.close();                processlabel.setText("Disconnected");             }             catch(IOException ie)             {             System.err.println("Error in input output.");             }          }          /*          This is executed when user clicks the Dial button.          */          if("dial".equals(actioncommand))          {             /*             Declare and initialize object of String class.             */             String portname=portnametextbox.getText();             if (portname==null)             {                JOptionPane.showMessageDialog(null," Please select one port name.","                No port choosen",JOptionPane.PLAIN_MESSAGE);                return;             }             else if (portname.trim().length()==0)             {                JOptionPane.showMessageDialog(null,"Please select one port name.","                No port choosen",JOptionPane.PLAIN_MESSAGE);                return;             }             String phoneno=phonenumbertextbox.getText();             if (phoneno==null)             {                JOptionPane.showMessageDialog(null," Please enter phone number.","                No phone number choosen",JOptionPane.PLAIN_MESSAGE);                return;             }             else if(phoneno.trim().length()==0)             {                JOptionPane.showMessageDialog(null," Please enter phone number.","                No phone number choosen",JOptionPane.PLAIN_MESSAGE);                return;             }             else             {                /*                Check for phone number validation.                */                String phonenoaftertrim=phoneno.trim();                String validstring="0123456789,";                for(int i=0;i<phonenoaftertrim.length();i++)                {                   if (validstring.indexOf(phonenoaftertrim.charAt(i))==-1)                   {                      JOptionPane.showMessageDialog(null," Please enter a valid phone number.","                      No phone number choosen",JOptionPane.PLAIN_MESSAGE);                      return;                   }                }                /*Calls the portOpen()method.*/                portOpen(phonenoaftertrim);             }          }       }    public static void main(String[] args) throws IOException,    NoSuchPortException,PortInUseException,Unsuppor tedCommOperationException     {       /*       Declare and initialize object of PortModem class.       */       PortModem portmodem=new PortModem();    }    /*    portOpen - This method opens port.    Parameters: phonenoaftertrim - objcet of String class.    Return Value: NA    */    public void portOpen(String phonenoaftertrim)     {       /*Get selected port.*/       commportid=portchooser.getSelectedIdentifier();       processlabel.setText(" Dialing number...");       switch (commportid.getPortType())        {          /*          This will be executed if selected port is Serial.           */          case CommPortIdentifier.PORT_SERIAL:          try          {             /*Try to open the port.*/             commport=commportid.open("Modem Application",1000);             commportid.addPortOwnershipListener(new OwnerShip());          }          catch(PortInUseException piu)          {             processlabel.setText("Port has not been opened.");          }          SerialPort serialport=(SerialPort)commport;          try          {             /*             Set parameters for serial port communication.             */             serialport.setSerialPortParams(BAUD, SerialPort.DATABITS_8,             SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);          }          catch(UnsupportedCommOperationException uco)          {             processlabel.setText("Port has not been opened.");          }          break;          /*          This will be executed if selected port is parallel.          */          case CommPortIdentifier.PORT_PARALLEL:          try          {             /*Try to open the port.*/             commport=commportid.open("Modem Applecation",1000);             commportid.addPortOwnershipListener(new OwnerShip());          }          catch(PortInUseException piu)          {             processlabel.setText("Port has not been opened.");          }          ParallelPort parallelport=(ParallelPort)commport;          break;          default:          throw new IllegalStateException("Unknown port type " + commportid);       }       try        {          /*Get Input stream.*/          is = new DataInputStream(commport.getInputStream());       }        catch (IOException e)        {          System.err.println("Can't open input stream: write-only");          is = null;       }       try       {          /*Get Output stream*/          os = new PrintStream(commport.getOutputStream(), true);       }       catch(IOException ie)       {          System.err.println("Can't open output string.");       }       try       {          /*Calls send method.*/          send("ATZ");          /*Calls expect method.*/          expect("OK");          /*Calls send method.*/          send("ATDT" + phonenoaftertrim);       }       catch(IOException ie)       {          System.err.println(ie);       }       try        {          is.close();          os.close();       }       catch(IOException ie)       {          System.err.println(ie);       }    }    /*    class OwnerShip - This is a inner class. It implements CommPortOwnershipListener     interface and override its methods.    Methods:    ownershipChange - Check to see ownership of a port.    */    class OwnerShip implements CommPortOwnershipListener    {       protected boolean owned = false;       public void ownershipChange(int owner)        {          switch (owner)           {             /*             Execute when end user clicks Dial button             */             case PORT_OWNED:             System.out.println("An open succeeded.");             owned = true;             cancelbutton.setEnabled(true);             dialbutton.setEnabled(false);             break;             /*             Execute when end user clicks Cancel button             */             case PORT_UNOWNED:             System.out.println("A close succeeded.");             cancelbutton.setEnabled(false);             dialbutton.setEnabled(true);             owned = false;             break;             case PORT_OWNERSHIP_REQUESTED:             if (owned)              {                if (JOptionPane.showConfirmDialog(null,"I've been asked to give up the port,                 should I?","",JOptionPane.OK_CANCEL_OPTION) == 0)                commport.close();             }             else             {             System.out.println("Somebody else has the port");             }          }       }    }    /*    send - This method sends phone number to modem.    Parameters: s - object of String class.    Return Value: NA    */    protected void send(String s) throws IOException     {       if (start)        {          System.out.print(">>> ");          System.out.print(s);          System.out.println();       }       os.print(s);       os.print("\r\n");       if (!expect(s))        {          System.err.println("WARNING: Modem did not echo command.");       }    }    /*    expect - This method receives response of modem    Parameters:   exp - objcet of String class.    Return Value: NA    */    protected boolean expect(String exp) throws IOException     {       response = is.readLine();       if (start)        {          System.out.print(response);          System.out.println();       }       return response.indexOf(exp) >= 0;    } } 
end example

Download this listing.

In the above listing, the main() method creates an instance of the PortModem class, which generates the main window of the Modem Dialer application, as shown in Figure 3-2:

click to expand: this figure shows the user interface of the modem dialer application. the user interface consists of two labels called port name and phone number, two text boxes, and four buttons that are browse, dial, cancel, and close.
Figure 3-2: The Modem Dialer Application Window

In the user interface:

  • The Port Name text box: Specifies the port to which the modem is connected.

  • The Phone Number text box: Specifies the phone number to which an end user wants to connect.

  • The Browse button: Invokes the user interface that the PortChooser.java file creates.

  • The Dial button: Enables an end user to make a phone call to the number specified in the Phone Number text box.

  • The Cancel button: Ends the current call.

  • The Close button: Terminates the Modem Dialer application.

The PortModem class contains an inner class called OwnerShip. The OwnerShip class implements the CommPortOwnershipListener interface provided by the JCA API and overrides the methods of the CommPortOwnershipListener interface. The various methods defined in the PortModem class are:

  • actionPerformed(): Acts as an event listener and activates an appropriate method based on the button that the end user clicks. When the end user clicks the Dial button, the actionPerformed() method validates the phone number specified in the Phone Number text box. In addition, the actionPerformed() method verifies the port selected in the Port Name text box. The actionPerformed() method calls the portOpen() method to open the selected port.

  • send(): Sends the phone number specified by the end user to the modem.

  • expect(): Receives the response of the modem through the Serial port.

  • portOpen(): Opens the port that the end user selects from the Port Name text box. The portOpen() method creates an instance of the DataInputStream class using the input stream of the Serial port opened for communication. The DataInputStream class sends data to the modem with the help of the Serial port. The portOpen() method also creates an instance of the PrintStream class using the output stream of the Serial port opened for communication. The PrintStream class accepts the response of the modem with the help of the Serial port.

The portOpen() method also invokes the send() and expect() methods to communicate with the Serial port. The portOpen() method invokes the send() method with the ATZ parameter to check if the modem is ready for communication. If the modem responds successfully, the portOpen() method invokes the send() method with two parameters, ATDT and the phone number specified by the end user. The ATDT parameter commands the modem to dial a specified phone number.




Developing Applications Using JCA
Developing Applications Using JCA
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 43

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