Choosing a Port


You need to know what ports are available on a given computer.


Use CommPortIdentifier.getPortIdentifiers( ) to return the list of ports.


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 JComboBoxes 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.