Creating the User Interface and Implementing Business Logic


The PortCommunication.java file is the main file of the Serial Communication application. This file creates a user interface for the Serial Communication application. Listing 5-1 shows the PortCommunication.java file:

Listing 5-1: The PortCommunication.java File

start example
 import javax.comm.*; /*Imports required java.i/o package classes.*/ import java.io.File; import java.io.*; /*Imports required Filedialogbox classes.*/ import javax.swing.filechooser.*; /*Imports required javax.swing package classes.*/ import javax.swing.*; import javax.swing.event.*; /*Imports required java.awt package classes.*/ import java.awt.*; import java.awt.event.*; /*Import the java.util package classes.*/ import java.util.*; /* class PortCommunication - This class is the main class of the application.  This class initializes the interface and loads all components like the menubar,  textareas, and buttons before displaying the result. Constructor:    PortCommunication-This constructor creates GUI. Methods:    createGUI - This method creates GUI.    actionPerformed - This method describes which action will be performed on which component.    getExtension - This method gives file extension.    setConnectionParameters    openPort - This method opens port.    closePort - This method closes port.    writeFile - This method write contents of textarea into file.    save - This method save contents of textarea into file.    main - This method creates the main window of the application and displays all the components. */ public class PortCommunication extends JFrame implements ActionListener, SerialPortEventListener, CommPortOwnershipListener {    /*Declare object of JMenuBar class.*/    private JMenuBar menubar;    /* Declare object of JMenu class.*/    private JMenu filemenu;    /*Declare object of JMenuItem class.*/    private JMenuItem openmenuitem, savemenuitem, exitmenuitem, property menuitem;    /*Declare object of JTextArea class.*/    private JTextArea sendertextarea;    private JTextArea recevertextarea;    /*Declare object of JScrollPane class.*/    private JScrollPane senderscrollpane;    private JScrollPane receverscrollpane;    /*Declare object of JPanel class.*/    private JPanel buttonpanel;    private JPanel textareapanel;    /*Declare object of JButton class.*/    private JButton openportbutton;    private JButton closeportbutton;    /*Declare object of JComboBox class.*/    private JComboBox comportcombo;    /*     Declare and Initialize object of File class.       */    File file=null;    /*Declare object of JFileChooser class.*/    JFileChooser openfile;    /* Declare object of OutputStream class.*/    private OutputStream os;    /*Declare object of InputStream class.*/    private InputStream is;    /*Declare object of KeyHandler class.*/    private KeyHandler keyHandler;    /*Declare object of PortPropertyPage class.*/    PortPropertyPage portpropertypage;    /*     Declare object of CommPortIdentifier class.    */    private CommPortIdentifier opencomm;    /*Declare object of SerialPort class.*/    private SerialPort sport;    boolean open=false;    private StringBuffer outputbuffer=new StringBuffer();    public PortCommunication()    {       super("Serial Communication");       createGUI();    }    /*    createGUI: It is called to create menubar, text areas, and button.       Parameter: N/A       Return Value: N/A    */    public void   createGUI()    {       /*       Set location at which window will be displayed.       */       Dimension  scrnSize = Toolkit.getDefaultToolkit().getScreenSize();       setLocation((scrnSize.width / 2) - 250, (scrnSize.height / 2) - 250);       /*        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("Error in setting WLAF"+e);       }       /* Set window's close operation. */       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       addWindowListener(new WindowAdapter()       {          public void windowOpened(WindowEvent we)          {             System.out.println("Window opened!");          }       });       /*        Declare and Initialize object of Container class with return value of getContentPane function.       */       Container contentpane=getContentPane();       /*Initialize object of JFileChooser.*/       openfile=new JFileChooser();       /*Set file filter for openfile object.*/          openfile.setFileFilter(new javax.swing.filechooser.FileFilter ()        {       /*       accept: Override method of FileFilter class.       Parameter: f - Object of File class.       Return Value:boolean       */       public boolean accept(File f)        {          if (f.isDirectory())           {             return true;          }          String name = f.getName();          if (name.endsWith(".txt"))           {             return true;          }          return false;       }       /*       getDescription: Override method of FileFilter class.       Parameter: NA       Return Value: String       */             public String getDescription()        {          return ".txt";             }            });       /*        Initialize the object of JMenuBar class.       */       menubar=new JMenuBar();       /*        Initialize the object of JMenu class.       */       filemenu=new JMenu("File");       filemenu.setMnemonic('f');       /*        Initialize the object of JMenuItem class.Set hot key as 's' and add to file menu.       */       savemenuitem=new JMenuItem("Save");       savemenuitem.addActionListener(this);       savemenuitem.setMnemonic('s');       savemenuitem.setActionCommand("save");       filemenu.add(savemenuitem);       /*        Initialize the object of JMenuItem class. Set hot key as 'o' and add to file menu.       */       propertymenuitem=new JMenuItem("Properties");       propertymenuitem.addActionListener(this);       propertymenuitem.setActionCommand("open_property");       propertymenuitem.setMnemonic('o');       filemenu.add(propertymenuitem);       /*        Initialize the object of JMenuItem class.Set hot key as 'e' and add to file menu.       */       exitmenuitem=new JMenuItem("Exit");       exitmenuitem.addActionListener(this);       exitmenuitem.setActionCommand("exit");       exitmenuitem.setMnemonic('e');       filemenu.add(exitmenuitem);       /*        Initialize the object of JMenu class.       */       menubar.add(filemenu);       setJMenuBar(menubar);       /* Initialize object of JPanel.*/       buttonpanel=new JPanel();       /*        Initialize object of JButton, set title, hotkey and action command of this button       */       openportbutton=new JButton("<html>O<u>p</u>en Port</html>");       openportbutton.setMnemonic('p');       openportbutton.setActionCommand("open_port");       openportbutton.addActionListener(this);       /*        Initialize object of JButton, set title, hotkey and action command of this button       */       closeportbutton=new JButton("<html><u>C</u>lose Port</html>");       closeportbutton.setMnemonic('C');       closeportbutton.setEnabled(false);       closeportbutton.setForeground(Color.gray);       closeportbutton.setActionCommand("close_port");       closeportbutton.addActionListener(this);       /*        Declare and initialize objects of GridBagLayout class.       */       GridBagLayout gridbaglayout=new GridBagLayout();       /*        Declare and initialize object of GridBagConstraints class.       */       GridBagConstraints gridbagconstraint=new GridBagConstraints();       /*       Set buttonpanel's layout as gridbaglayout       */       buttonpanel.setLayout(gridbaglayout);       /*       Set properties of gridbagconstraint       */       gridbagconstraint.fill=GridBagConstraints.HORIZONTAL;       gridbagconstraint.insets=new Insets(5, 5, 5, 5);       gridbagconstraint.gridx=0;       gridbagconstraint.gridy=0;       gridbagconstraint.anchor=GridBagConstraints.CENTER;       gridbaglayout.setConstraints(openportbutton, gridbagconstraint);       /*       Add button to buttonpanel pane       */       buttonpanel.add(openportbutton);       /*       Set properties of gridbagconstraint       */       gridbagconstraint.gridx=1;       gridbagconstraint.gridy=0;       gridbagconstraint.anchor=GridBagConstraints.CENTER;       gridbaglayout.setConstraints(closeportbutton, gridbagconstraint);       /*       Add button to buttonpanel pane       */       buttonpanel.add(closeportbutton);       contentpane.add(buttonpanel,BorderLayout.SOUTH);       textareapanel=new JPanel(new GridLayout(2,1,5,5));       /*       Initialize objects of JTextArea class.       */       sendertextarea=new JTextArea();       recevertextarea=new JTextArea();       /*       Set recevertextarea as non editable.       */       recevertextarea.setEditable(false);       /*       Initialize objects of JScrollPane class.       */       senderscrollpane=new JScrollPane(sendertextarea);       receverscrollpane=new JScrollPane(recevertextarea);       /*       Add scrollPanes to textareapanel       */       textareapanel.add(senderscrollpane);       textareapanel.add(receverscrollpane);       contentpane.add(textareapanel,BorderLayout.CENTER);       /*       Initialize object of PortPropertyPage       */       portpropertypage=new PortPropertyPage();       /*       Add actionlistener with ok button of PortPropertyPage class.       */       portpropertypage.getOkButton().addActionListene r(new ActionListener()       {          public void actionPerformed(ActionEvent ae)          {             if (open)             {                System.out.println(portpropertypage.getCommPortName()+"--"+sport.getName());                if (portpropertypage.getCommPortName()==sport.getName())                {                   setConnectionParameters();                   }                else                {                   System.out.println("Port can't be changed while another port is open");                }             }             else             {                setConnectionParameters();             }             portpropertypage.setVisible(false);          }       });       /*       Add actionlistener with cancel button of PortPropertyPage class.       */       portpropertypage.getCancelButton().addActionListener(new ActionListener()       {          public void actionPerformed(ActionEvent ae)          {             portpropertypage.setVisible(false);          }       });       /*       Set size of main window.       */       setSize(400,300);       setVisible(true);    }    /*  Main method that creates the instance of the PortCommunication class.    */    public static void main(String args[])    {       PortCommunication portcommunication=new PortCommunication();    }    /*    actionPerformed - This method is called when the user clicks the Open Port or     Close Port button, selects file or property menu item.    Parameters: ae - an ActionEvent object containing details of the event.    Return Value: NA     */    public void actionPerformed(ActionEvent ae)    {    String componentid=ae.getActionCommand();    /*    This is executed when user clicks the Open port button.    */    if (componentid=="open_port")    {       if (openPort())       {          System.out.println("open");          openportbutton.setEnabled(false);          openportbutton.setForeground(Color.gray);          closeportbutton.setEnabled(true);          closeportbutton.setForeground(Color.black);          System.out.println(open);       }    }    /*    This is executed when user clicks the Close port button.    */    if (componentid=="close_port")    {       if (closePort())       {          System.out.println("close");          closeportbutton.setEnabled(false);          openportbutton.setEnabled(true);          closeportbutton.setForeground(Color.gray);          openportbutton.setForeground(Color.black);          System.out.println(open);       }    }    /*    This is executed when user clicks the Open property Page menu item.    */    if (componentid=="open_property")    {       portpropertypage.setVisible(true);    }    /*    This is executed when user clicks the Save menu item.    */    if (componentid=="save")    {       save();    }    /*    This is executed when user clicks the Exit menu Item.    */    if (componentid=="exit")    {       System.exit(0);    } }    /* closePort - This method is called to close an opened port. Parameters: NA Return Value:boolean  */ public boolean closePort() {    if (!open)     {       return false ;    }    sendertextarea.removeKeyListener(keyHandler);    if (sport != null)     {       try        {          /* Close the I/O streams.*/          os.close();          is.close();       }       catch (IOException e)        {          System.err.println(e);       }       /*Close serial port.*/       sport.close();       opencomm.removePortOwnershipListener(this);    }    open=false;    return true; }    /*    openPort - This method is called to open a closed port.       Parameters: NA       Return Value:boolean    */    public boolean openPort()    {       if (portpropertypage.getCommPortName()==null||portpropertypage.getCommPortName()=="")       {          JOptionPane.showMessageDialog(null," No port exists. "," Error ",JOptionPane.PLAIN_MESSAGE);         return false;       }       opencomm=portpropertypage.getCommPort();       try       {          sport=(SerialPort)opencomm.open("Serial Communication",2000);             try          {             setConnectionParameters();          }          catch(Exception e)          {             JOptionPane.showMessageDialog(null,"  Properties can not be set for this port. ","             Serial Communication ",JOptionPane.PLAIN_MESSAGE);          }       }       catch(PortInUseException pe)       {                    JOptionPane.showMessageDialog(null," Port is in use. "," Serial Communication ",JOptionPane.PLAIN_MESSAGE);       }       try       {          os = sport.getOutputStream();          is = sport.getInputStream();       }        catch (IOException e)        {          sport.close();          return false;         }       keyHandler = new KeyHandler(os);       sendertextarea.addKeyListener(keyHandler);       try        {          sport.addEventListener(this);       }       catch (TooManyListenersException e)        {          sport.close();          return false;       }       sport.notifyOnDataAvailabel(true);       sport.notifyOnBreakInterrupt(true);       try        {          sport.enableReceiveTimeout(30);       }       catch (UnsupportedCommOperationException e)        {          JOptionPane.showMessageDialog(null,"Serial Communication","          This operation is not supported by this port.",JOptionPane.PLAIN_MESSAGE);          sport.close();          return false;       }       opencomm.addPortOwnershipListener(this);       open=true;       return true;    }    /*    setConnectionParameters - This method is called to set serial port properties.    Parameters: NA    Return Value:boolean     */    public void setConnectionParameters()    {       int oldbaudrate= 0;       int olddatabits =0;       int oldstopbits = 0;       int oldparity = 0;       int oldflowcontrol =0;       if (open)       {           oldbaudrate = sport.getBaudRate();           olddatabits = sport.getDataBits();           oldstopbits = sport.getStopBits();           oldparity = sport.getParity();           oldflowcontrol = sport.getFlowControlMode();          try          {             sport.setSerialPortParams(portpropertypage.getBaudRate(),             portpropertypage.getDatabits(), portpropertypage.getStopbits(), _             portpropertypage.getParity());          }           catch (UnsupportedCommOperationException e)           {             portpropertypage.setBaudRate(oldbaudrate);             portpropertypage.setDatabits(olddatabits);             portpropertypage.setStopbits(oldstopbits);             portpropertypage.setParity(oldparity);          }          try           {             sport.setFlowControlMode(portpropertypage.getFlowControlIn() |             portpropertypage.getFlowControlOut());          }          catch (UnsupportedCommOperationException ue)           {          }       }    }    /*    getExtension: This method will extract file extension from file.     Parameter: f - object of File class    Return Value: file extension    */    public String getExtension(File f)    {       if(f != null)        {          String filename = f.getName();          int i = filename.lastIndexOf('.');          if(i>0 && i<filename.length()-1)           {             return filename.substring(i+1).toLowerCase();          };       }       return null;    }    /*    save: This method will save to the contents of textarea into a file.       Parameter- NA       Return Value:boolean    */    public boolean save()    {       int result = openfile.showSaveDialog(this);       if( result == JFileChooser.CANCEL_OPTION)       {          return true;       }       else if( result == JFileChooser.APPROVE_OPTION)       {          file = openfile.getSelectedFile();          if( file.exists())          {             int response = JOptionPane.showConfirmDialog(null,             "Overwrite existing file?",             "Confirm Overwrite",             JOptionPane.OK_CANCEL_OPTION,             JOptionPane.QUESTION_MESSAGE);             if( response == JOptionPane.CANCEL_OPTION)                return false;          }          return writeFile(file, sendertextarea.getText());       }       else       {          return false;       }    }    /*    writeFile: This method will save to the contents of textarea into a file.       Parameter- file - object of File class, dataString - Object of String class.       Return Value:boolean    */    public static boolean writeFile(File file, String dataString)    {       try       {          PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(file)));          out.print(dataString);          out.flush();          out.close();       }       catch (IOException e)       {          return false;       }       return true;    }    class KeyHandler extends KeyAdapter     {       OutputStream os;       public KeyHandler(OutputStream os)        {          super();          this.os = os;       }       public void keyTyped(KeyEvent evt)        {             char newCharacter = evt.getKeyChar();          try           {             if ((int)newCharacter==10)             {                for (int i=0;i<outputbuffer.length() ;i++ )                {                   os.write((int)outputbuffer.charAt(i));                }                outputbuffer=new StringBuffer();             }             else             {                outputbuffer.append(newCharacter);             }             System.out.println((int)newCharacter);          }          catch (IOException e)           {             System.err.println("OutputStream write error: " + e);          }        }    }    public void ownershipChange(int type)     {       if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED)        {       }    }    public void serialEvent(SerialPortEvent e)     {       /*       Create a StringBuffer and int to receive input data.       */       StringBuffer inputBuffer = new StringBuffer();       int newData = 0;       /* Determine type of event.*/       switch (e.getEventType())        {          case SerialPortEvent.DATA_AVAILABEL:          while (newData != -1)           {             try              {                newData = is.read();                if (newData == -1)                 {                   break;                }                if ('\r' == (char)newData)                 {                   inputBuffer.append('\n');                }                else                 {                   inputBuffer.append((char)newData);                }             }             catch (IOException ex)              {                System.err.println(ex);                return;             }          }          /* Append received data to messageAreaIn.*/          recevertextarea.append(new String(inputBuffer));             break;          /*          If break event append BREAK RECEIVED message.          */          case SerialPortEvent.BI:             recevertextarea.append("\n--- BREAK RECEIVED ---\n");       }       }    } 
end example

Download this listing.

In the above listing, the main() method creates an instance of the PortCommunication class. This class generates the main window of the Serial Communication application, as shown in Figure 5-2:

click to expand: this figure shows the user interface of the serial communication application.
Figure 5-2: The Serial Communication Window

The user interface of the Serial Communication application displays a File menu that contains three menu options, Save, Properties, and Exit, as shown in Figure 5-3:

this figure shows the file menu that contains three menu options, save, properties, and exit.
Figure 5-3: The File Menu

The Save menu option saves the data sent and received using the ports.

The Properties menu option enables the end user to set the properties of the port used for communication. When the end user clicks this option, it creates an instance of the PortPropertyPage.java class to open a dialog box that end users can use to change the properties of the selected port.

The Exit menu option enables the end user to exit from the application.

The user interface of the Serial Communication application also contains two text panes. The upper text pane sends data through a selected and opened port. The lower pane displays the data received using the selected and opened port.

In addition to text panes and menus, the user interface of the Serial Communication application also displays two buttons, Open Port and Close Port, to open and close the port used for communication.

When an end user clicks any button, the Serial Communication application invokes the actionPerformed() method. This method acts as an event listener and activates an appropriate method based on the button that the end user clicks. For example, when the end user clicks the Open Port button, the actionPerformed() method opens a port for communication. The actionPerformed() method invokes the setConnectionParameters() method, which returns the properties last saved by the end user. When the end user clicks the Close Port button, the actionPerformed() method closes the port that was opened for communication.




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