Choosing a Port
Problem
You need to know what ports are available on a given computer.
Solution
Use CommPortIdentifier.getPortIdentifiers( )
to return the list of
ports.
Discussion
There are many kinds of computers out there. It’s unlikely that
you’d find yourself running on a desktop computer with no
serial ports, but you might find that there is only one and
it’s already in use by another program. Or you might want a
parallel port and find that the computer has only serial ports. This
program shows you how to use the static
CommPortIdentifier
method
getPortIdentifiers( )
. This gives you an
Enumeration
(Section 7.5) of the
serial and parallel ports available on your system. My routine
populate( )
processes this list and loads it into
a pair of JComboBoxes
(graphical choosers; see
Section 13.2), one for serial ports and one for
parallel (there is also a third, unknown, to cover future expansion
of the API). The routine makeGUI
creates the
JComboBox
es and arranges to notify us when the
user picks one from either of the lists. The name of the selected
port is displayed at the bottom of the window. So that you
won’t have to know much about it to use it, there are public
methods getSelectedName
( ), which returns the name
of the last port chosen by either JComboBox
and
getSelectedIdentifier( )
, which returns an object
called a CommPortIdentifier
corresponding to the
selected port name. Figure 11-1 shows the port chooser in action.
Figure 11-1. The Communications Port Chooser in action
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.