import javax.comm.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class PortOpener implements CommPortOwnershipListener { protected CommPortIdentifier portID; protected CommPort port = null; protected Button openButton; protected boolean openFlag = false; protected String appName; public PortOpener(String appName, String portName){ this.appName = appName; Frame frame = new Frame(appName); frame.setBounds(100, 100, 100, 80); openButton = new Button("Open"); frame.add(openButton); frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); openButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ // ポートの状態により処理を変化させる if(openFlag){ close(); }else{ open(); } } }); frame.setVisible(true); try{ // CommPortIdentifier を取得 portID = CommPortIdentifier.getPortIdentifier(portName); // ポートの専有状態の監視を行うためのリスナを登録 portID.addPortOwnershipListener(this); }catch(NoSuchPortException ex){ System.out.println(portName + "can't be found."); ex.printStackTrace(); System.exit(1); } } public void open(){ try{ openButton.setLabel("Requesting...."); openButton.setEnabled(false); // ポートのオープン // タイムアウトは 1分間=60,000ms port = portID.open(appName, 60000); openButton.setEnabled(true); // ボタンの文字列を変更 openButton.setLabel("Close"); openFlag = true; }catch(PortInUseException ex){ // タイムアウトを過ぎた場合 System.out.println(portID.getName() + " is owned by someone."); } } public void close(){ if(port != null){ // ポートをクローズ port.close(); port = null; // ボタンの文字列を変更 openButton.setLabel("Open"); openFlag = false; } } public void ownershipChange(int type){ switch(type){ case PORT_OWNED: // ポートが専有されている場合 System.out.println(portID.getName() + " is Owned by " + portID.getCurrentOwner()); break; case PORT_UNOWNED: // ポートが専有されていない場合 System.out.println(portID.getName() + " is Unowned"); break; case PORT_OWNERSHIP_REQUESTED: // ポートの専有を要求している場合 System.out.println(portID.getName() + " is Requested"); break; } } public static void main(String args[]){ PortOpener opener = new PortOpener(args[0], args[1]); } }