Creating the User Interface


The PortDescription.java file creates a user interface, which lets the end user list all serial and parallel ports attached to a computer and open any of the selected port for input/output operations using the CommPortIdentifier class. The PortDescription.java file uses the CommPort and ParallelPort classes to enable the end user to communicate through the selected port opened by the CommPortIdentifier class.

Listing 2-1 shows the code of the PortDescription.java file:

Listing 2-1: The PortDescription.java File

start example
 /* Imports required Comm classes. */ import javax.comm.*; /* Imports required I/O classes. */ import java.io.*; /* Imports required AWT classes. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /* Imports required Util classes. */ import java.util.*; /* Class PortDescription - This class is the main class of the application.  This class initializes the interface and loads all components like the button and  listbox before displaying the result. Constructor: PortDescription - This constructor creates GUI. Methods: getPortDescription - This method gives port description. openPort - This method opens a selected port. getSerialPorts - This method fills list of serial ports. getParallelPorts - This method fills list of parallel ports. emptyList - This method clears a list. main - This method creates the main window of the application and displays all the components. */ public class PortDescription implements ActionListener,ListSelectionListener  {    /* Declare object of JFrame class. */    JFrame frame;    /* Declare object of Enumeration class. */    Enumeration pList;     /* Declare objects of JLabel class. */    private JLabel apppagetitle;    private JLabel seriallabel;    private JLabel parallallabel;    /* Declare objects of JButton class. */    private JButton serialportbutton;     private JButton commportbutton;    private JButton openportbutton;    private JButton portdescriptionbutton;    /* Declare objects of JList class. */    private JList listserial;    private JList listcomm;    /*     Declare objects of DefaultListModel class.     */    private DefaultListModel listModelserial;    private DefaultListModel listModelcomm;    int descriptionpos;    int buttonwidth=140;    int buttonheight=25;    public PortDescription()     {       /*        Initialize and set the look and feel of the application to Windows Look and Feel.       */        try        {           UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());       }       catch(Exception e)       {          /*           If an error occurs while loading the Windows Look and Feel, an           error is printed and the application is closed.           */          System.out.println("Error setting window environment: " + e);       }       try       {          /*           Initialize the object of the JFrame class and set the Title.          */          frame=new JFrame("Ports Application");          /*           Initialize the object of the JButton class and set the Title.          */          Container pane=frame.getContentPane();          /*           Set the layout of the frame as Null.           */          pane.setLayout(null);          /*           Set background color as white.           */          pane.setBackground(Color.white);          /*          Initialize a new button, Set hot key as 'S' and add to content pane.          */          serialportbutton=new JButton("List Serial Ports");          serialportbutton.setMnemonic('S');          serialportbutton.setActionCommand("serial");          serialportbutton.setPreferredSize(new Dimension(buttonwidth, buttonheight));          serialportbutton.addActionListener(this);          pane.add(serialportbutton);          /*          Initialize a new button, Set hot key as 'C' and add to content pane.          */          commportbutton=new JButton("List Parallel Ports");          commportbutton.setMnemonic('C');          commportbutton.setActionCommand("parallel");          commportbutton.setPreferredSize(new Dimension(buttonwidth, buttonheight));          commportbutton.addActionListener(this);          pane.add(commportbutton);          /*          Initialize a new button, Set hot key as 'O' and add to content pane.          */          openportbutton=new JButton("Open Port");           openportbutton.setMnemonic('O')          openportbutton.setActionCommand("open");          openportbutton.setPreferredSize(new Dimension(buttonwidth, buttonheight));          openportbutton.addActionListener(this);          pane.add(openportbutton);          /*          Initialize a new button, Set hot key as 'D' and add to content pane.          */          portdescriptionbutton=new JButton("Port Description");           portdescriptionbutton.setMnemonic('D');          portdescriptionbutton.setActionCommand("description");          portdescriptionbutton.setPreferredSize(new Dimension(buttonwidth, buttonheight));          portdescriptionbutton.addActionListener(this);          pane.add(portdescriptionbutton);          openportbutton.setEnabled(false);          /* Initialize a new label and add to content pane. */          seriallabel=new JLabel("Serial Ports");          seriallabel.setFont(new Font("Verdana", Font.BOLD, 14));          pane.add(seriallabel);          /* Initialize a new label and add to content pane. */          parallallabel=new JLabel("Parallel Ports");          parallallabel.setFont(new Font("Verdana", Font.BOLD, 14));          pane.add(parallallabel);          /*           Initialize a new label and add to content pane.           */          apppagetitle=new JLabel("Port Information Application");          apppagetitle.setFont(new Font("Verdana", Font.BOLD, 14));          pane.add(apppagetitle);          /*           Declare and initialize the object of Insets class.          */          Insets insets = pane.getInsets();          /*           Initialize the object of DefaultListModel class.          */          listModelserial = new DefaultListModel();          /*           Initialize the object of DefaultListModel class.          */          listModelcomm = new DefaultListModel();          /*           Initialize the object of JList class.           */          listserial = new JList(listModelserial);          listcomm=new JList(listModelcomm);          /*          Set the selection mode of listserial as single selection.           Declare and initialize the object of JScrollPane. Set dimension.           Add list to scroll pane and scroll pane to frame's content pane.          */          listserial.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);          listserial.addListSelectionListener(this);          listserial.setVisibleRowCount(10);          JScrollPane listScrollPane = new JScrollPane(listserial);          listScrollPane.setPreferredSize(new Dimension(250,200));          Dimension size=listScrollPane .getPreferredSize();          listScrollPane.setBounds(80, 90, size.width, size.height);          pane.add(listScrollPane);          /*          Set the selection mode of listcomm as single selection.           Declare and initialize the object of JScrollPane.           Set dimension. Add list to scroll pane add scroll pane to frame's content pane.          */          listcomm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);          listcomm.addListSelectionListener(this);          listcomm.setVisibleRowCount(10);          listScrollPane = new JScrollPane(listcomm);          listScrollPane.setPreferredSize(new Dimension(250,200));          size=listScrollPane .getPreferredSize();          listScrollPane.setBounds(380, 90, size.width, size.height);          pane.add(listScrollPane);          /*          Declare object of Dimension class and initialize it with getScreenSize() method.          */          Dimension  scrnSize = Toolkit.getDefaultToolkit().getScreenSize();          /*           Set location at which window will be displayed.           */          frame.setLocation((scrnSize.width / 2) - 350, (scrnSize.height / 2) - 250);          /* Initialize left margin. */          descriptionpos=70;          size = serialportbutton.getPreferredSize();          /*           Set position of the serialportbutton button.           */          serialportbutton.setBounds(descriptionpos+5, 500 + insets.top, size.width, size.height);          descriptionpos=descriptionpos+size.width;          size = commportbutton.getPreferredSize();          /*           Set position of the commportbutton button.           */          commportbutton.setBounds(descriptionpos+5, 500 + insets.top, size.width, size.height);          descriptionpos=descriptionpos+size.width;          size = portdescriptionbutton.getPreferredSize();          /*           Set position of the portdescriptionbutton button.           */          portdescriptionbutton.setBounds(descriptionpos+5, 500 + insets.top, size.width, size.height);          descriptionpos=descriptionpos+size.width;          size = openportbutton.getPreferredSize();          /*           Set position of the openportbutton button.           */          openportbutton.setBounds(descriptionpos+ 5, 500 + insets.top, size.width, size.height);          size = seriallabel.getPreferredSize();          /*           Set position of the seriallabel label.           */          seriallabel.setBounds(80 + insets.left, 60 + insets.top, size.width, size.height);          size = parallallabel.getPreferredSize();          /*           Set position of the parallallabel label.           */          parallallabel.setBounds(380 + insets.left, 60 + insets.top, size.width, size.height);          size=apppagetitle.getPreferredSize();          /*           Set position of the apppagetitle label.           */          apppagetitle.setBounds(250 + insets.left,  insets.top, size.width, size.height);          /*           Set the size of the Application frame.           */          frame.setSize(700,600);          frame.setVisible(true);          /*          addWindowListener - It contains the windowClosing() method.          windowClosing: It is called when the user clicks the cancel button of the Window. It closes the main window.          Parameter:           we - Object of WindowEvent class.          Return Value: NA          */          frame.addWindowListener(new WindowAdapter()          {             public void windowClosing(WindowEvent we)             {                System.exit(0);             }          });       }       catch(Exception e)       {          System.err.println(e);          e.printStackTrace();       }    }    /*    valueChanged: It is called when the user selects a listitem from the list.    Parameter:     le - Object of ListSelectionEvent class.    Return Value: NA    */    public void valueChanged(ListSelectionEvent le)    {       if(le.getSource()==listcomm)       {          if (listserial.getSelectedIndex()!=-1)          {             if (le.getValueIsAdjusting())             {                listserial.clearSelection();             }          }       }       else if(le.getSource()==listserial)       {          if(listcomm.getSelectedIndex()!=-1)          {             if (le.getValueIsAdjusting())             {                listcomm.clearSelection();             }          }       }    }    /*    actionPerformed - This method is called when the user clicks the Get Serial Ports,     Get Comm Ports, Open Port or Port Description button.    Parameters:       ae - An ActionEvent object containing details of the event.    Return Value: NA    */    public void actionPerformed(ActionEvent e)    {       /*       This is executed when the end user clicks the Get Serial Ports button.       */       if ("serial".equals(e.getActionCommand()))        {          getSerialPorts();       }       /*       This is executed when the end user clicks the Get Parallel Ports button.       */       else if("parallel".equals(e.getActionCommand()))        {          getParallelPorts();       }       /*       This is executed when the end user clicks the Port Description button.       */       else if("description".equals(e.getActionCommand()))       {          getPortDescription();       }       /*       This is executed when the end user clicks the Open Port button.       */       else if("open".equals(e.getActionCommand()))       {          openPort();       }    }    /*    getPortDescription - This method open a new window to show port description of selected port.    Parameters: NA    Return Value: NA    */    public void getPortDescription()    {       /*        Declare and initialize String objects.        */       String name="port";       String isportopen="Not Open";       /*        Declare and initialize CommPort objects.        */       CommPort port =null;       ShowDescriptionWindow descriptionwindow;       descriptionwindow=new ShowDescriptionWindow();       /*       If the end user selected a port from serial port list       */       if (listserial.getSelectedIndex()!=-1)       {          name= listModelserial.getElementAt(listserial.getSelectedIndex()).toString();          descriptionwindow.setPortType("Serial port ");       }       /*        Else, the user selected a port from Parallel port list       */       else if(listcomm.getSelectedIndex()!=-1)       {          name = listModelcomm.getElementAt(listcomm.getSelectedIndex()).toString();          descriptionwindow.setPortType("Parallel port ");       }       try       {          CommPortIdentifier commport = javax.comm.CommPortIdentifier.getPortIdentifier(name);          try          {             /* Try to open port. */             port= commport.open("PortDescription",20);             descriptionwindow.isPortOpen("Not Open");             if(commport.getPortType() == CommPortIdentifier.PORT_PARALLEL)             {                ParallelPort pport = (ParallelPort)port;                int mode = pport.getMode();                switch (mode)                 {                   case ParallelPort.LPT_MODE_ECP:                   descriptionwindow.setPortMode("ECP");                   break;                   case ParallelPort.LPT_MODE_EPP:                   descriptionwindow.setPortMode("EPP");                   break;                   case ParallelPort.LPT_MODE_NIBBLE:                   descriptionwindow.setPortMode("Nibble Mode");                   break;                   case ParallelPort.LPT_MODE_PS2:                   descriptionwindow.setPortMode("Byte mode");                   break;                   case ParallelPort.LPT_MODE_SPP:                   descriptionwindow.setPortMode("Compatibility mode");                   break;                   default:                }                if (port!=null)                {                   port.close();                }             }          }          catch(PortInUseException pe)          {             descriptionwindow.isPortOpen("Open");             /*             Declare the String object and initialize it with a value returned by the getCurrentOwner() method.             */             String ownername = commport.getCurrentOwner();             if( ownername == null)             {                descriptionwindow.ownerName("unidenified");             }             else             {                descriptionwindow.ownerName(ownername);             }          }          descriptionwindow.portName(commport.getName());          descriptionwindow.showMessage(frame);          descriptionwindow.setResizable(false);       }       catch(NoSuchPortException e)       {          descriptionwindow.portNotExists("yes");       }    }    /*    openPort - This method try to open selected port for communication, if port is in     use or does not exists then this displays an error message to the end user.    Parameters: NA    Return Value: NA    */    public void openPort()    {       /* Declare and initialize String objects. */       String name="";       String porttype="Unknown port ";       CommPort port =null;       if (listserial.getSelectedIndex()!=-1)       {          name= listModelserial.getElementAt(listserial.getSelectedIndex()).toString();          porttype="Serial port ";       }       else if(listcomm.getSelectedIndex()!=-1)       {          name = listModelcomm.getElementAt(listcomm.getSelectedIndex()).toString();          porttype="Parallel port ";       }       try       {          CommPortIdentifier commport = javax.comm.CommPortIdentifier.getPortIdentifier(name);          try          {             port= commport.open("PortListOpen",20);             int userchoice=JOptionPane.showConfirmDialog(null,porttype+name+" has been             successful opened. Click Yes to close this port.","Open Port",JOptionPane.YES_NO_OPTION);             if (userchoice==0)             {                if (port!=null)                {                   port.close();                }             }          }          catch(PortInUseException pe)          {             String ownername = commport.getCurrentOwner();             if( ownername == null)             {                JOptionPane.showMessageDialog(null,"Open failed for "+porttype+name+".                 This is owned by unidentified application","Open Port",JOptionPane.PLAIN_MESSAGE);             }             else             {                if ("Port currently not owned".equals(ownername))                {                   JOptionPane.showMessageDialog(null,"Open failed for "+porttype+name+". "                   +ownername+".","Open Port",JOptionPane.PLAIN_MESSAGE);                }                else                {                   JOptionPane.showMessageDialog(null,"Open failed for "+porttype+name+". Port owned by "                    +ownername,"Open Port",JOptionPane.PLAIN_MESSAGE);                }             }          }       }       catch(NoSuchPortException e)       {          JOptionPane.showConfirmDialog(null,e,"Open Port",JOptionPane.YES_NO_OPTION);       }    }    /*    getSerialPorts - This method uses CommPortIdentifier API to get serial port names.    Parameters: NA    Return Value: NA    */    public void getSerialPorts()    {       emptyList("serial");       pList = CommPortIdentifier.getPortIdentifiers();       while (pList.hasMoreElements())        {          CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();          if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL)           {             /* Fill list from Serial ports. */             listModelserial.addElement(cpi.getName());          }       }       enableDisableOpenButton();    }    /*    getParallelPorts - This method uses CommPortIdentifier API to get parallel port names.    Parameters: NA    Return Value: NA    */    public void getParallelPorts()    {       emptyList("parallel");       pList = CommPortIdentifier.getPortIdentifiers();       while (pList.hasMoreElements())        {          CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();          if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL)           {             /* Fill list from Serial ports. */             listModelcomm.addElement(cpi.getName());          }       }       enableDisableOpenButton();    }    /*    emptyList - This method clears all list items from the list box.    Parameters: listtype - object of the String type.    Return Value: NA    */    public void emptyList(String listtype)    {       if (listtype=="serial")       {          listModelserial.clear();       }       else if(listtype=="parallel")       {          listModelcomm.clear();       }    }    /*    enableDisableOpenButton - This method disables/enables open port button     if serial and/or parallel port lists are empty/non-empty.    Parameters: NA    Return Value: NA    */    public void enableDisableOpenButton()    {       if ((listModelcomm.getSize()>0) || (listModelserial.getSize()>0))       {          openportbutton.setEnabled(true);       }       else       {          openportbutton.setEnabled(false);       }    }    /*     Main method that creates the instance of the PortDescription class.    */    public static void main(String[] args)     {       PortDescription pd=new PortDescription();    } } 
end example

Download this listing.

In the above listing, the main() method creates an instance of the PortDescription class. This class generates the main window of the Port Information application, as shown in Figure 2-2:

click to expand: this figure shows the port information application window. the window contains two list boxes, one for listing serial ports and the other for parallel ports, and four clickable buttons that allow the end user to perform various operations.
Figure 2-2: The Port Information Application User Interface

When an end user clicks any button on the Ports Application window, the Port Information 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 List Serial Ports button, the actionPerformed() method invokes the getSerialPorts() method. The getSerialPorts() method calls the getPortIdentifiers() method of the CommPortIdentifier class to get the enumeration of ports attached to a computer. Next, the getSerialPorts() method calls the getPortType() method of the CommPortIdentifier class to check for the serial port from the enumeration of ports. If the getPortType() method is equal to the CommPortIdentifier.PORT_SERIAL variable, the port is assumed to be a serial port. The method then identifies all the serial ports attached to a computer and lists the ports in the Serial Ports list box.

The List Parallel Ports button functions in a similar manner as that of the List Serial Ports button.

When an end user clicks the Open Port button, the actionPerformed() method invokes the openPort() method. The openPort() method calls the open() method of the CommPortIdentifier class to open the selected port for various input/output operations. If the selected port is already in use, the Port Information application throws an exception.

When the end user clicks the Port Description button, the actionPerformed() method invokes the getPortDescription() method. The getPortDescription() method retrieves the information of the selected port using the CommPortIdentifier class and creates an object of the ShowDescriptionWindow.java class to display the following information about the selected port:

  • Port Type

  • Port Name

  • Port Mode

  • Port Status

  • Owner Name




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