import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.util.*;
import javax.comm.*;

public class ManageComm extends JxFrame  
   implements ListSelectionListener, ActionListener
{
     CommPortIdentifier portId;
     Enumeration portEnum;
     
     JawtList status, portList;
     JRadioButton allPorts, openPorts;
     String lastItem;
        
  public ManageComm() {
     
     super ("Comm Manager");
     JPanel jp = new JPanel();
     getContentPane().add(jp);
     jp.setLayout (new BorderLayout());
     
     JPanel bp = new JPanel();
     jp.add("South", bp);
     
     //two radio buttons determine display
     allPorts = new JRadioButton("All ports");
     openPorts = new JRadioButton("Available ports", true);
     bp.add (openPorts);
     bp.add(allPorts);
     openPorts.addActionListener (this);
     allPorts.addActionListener (this);
     ButtonGroup bgrp = new ButtonGroup();
     bgrp.add(openPorts);
     bgrp.add(allPorts);
     
     portList = new JawtList(20);
     jp.add("West", portList);
     portList.addListSelectionListener (this);
     lastItem = "";       //index of last selected com port

     //now add status list on right
     status =  new JawtList(20);
     jp.add("Center", status);

     loadPorts();    //load into list box
     setSize(new Dimension(300,200));
     setVisible(true);
  }
 //------------------------------------
  public void actionPerformed(ActionEvent e) {
   loadPorts();
  }
 //------------------------------------
  public void valueChanged(ListSelectionEvent ls) {
     
     String st[] = portList.getSelectedItems ();
     if(! st[0].equals(lastItem)) {
      lastItem = st[0];      //debounces mouse unclick
      //get port name back from list box
      String portName = st[0];
      CommPort cp = CommPortManager.openPort (portName);
      if(cp == null)
         status.add(portName+" in use");
      else
         status.add(portName+" opened");
     }
  }
 //------------------------------------
  private void loadPorts() {
     if (allPorts.isSelected ())
         portEnum = CommPortManager.getAllPorts ();
     else
        portEnum = CommPortManager.getAvailablePorts ();
     portList.clear ();
     while (portEnum.hasMoreElements()) {
            portList.add((String)portEnum.nextElement ());
        }
  }
  //------------------------------------
  public static void main(String[] args) {
         new ManageComm();
    }

}
