asim.syslock.org
Tue 05 Dec 2006.  
Asim’s blog   /   Syslock archive



Home : Java

Name : RS 232 Port communication (GUI)

Description : This program uses the RS 232 port to communicate amongst computers.

Code :

/*
* Frame_1.java
*
* Created on March 7, 2004, 6:51 PM
*/


/**
*
* @author a
* @version
*/
import javax.comm.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
import java.util.Enumeration;
import javax.swing.*;

import java.awt.TextArea;

import java.util.TooManyListenersException;

class OKCancelDialog extends javax.swing.JDialog {
/** A return status code - returned if Cancel button has been pressed */
public static final int RET_CANCEL = 0;
/** A return status code - returned if OK button has been pressed */
public static final int RET_OK = 1;

/** Creates new form OKCancelDialog */
public OKCancelDialog(java.awt.Frame parent, boolean modal,String message) {
super (parent, modal);
initComponents ();
jLabel1.setText(message);
pack ();
}

/** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
public int getReturnStatus () {
return returnStatus;
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
private void initComponents() {
buttonPanel = new javax.swing.JPanel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
}
);

buttonPanel.setLayout(new java.awt.FlowLayout(2, 5, 5));

okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
}
);
buttonPanel.add(okButton);


cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
}
);
buttonPanel.add(cancelButton);


getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);


jLabel1.setText("jLabel1");

getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);

}

private void okButtonActionPerformed (java.awt.event.ActionEvent evt) {
doClose (RET_OK);
}

private void cancelButtonActionPerformed (java.awt.event.ActionEvent evt) {
doClose (RET_CANCEL);
}

/** Closes the dialog */
private void closeDialog(java.awt.event.WindowEvent evt) {
doClose (RET_CANCEL);
}

private void doClose (int retStatus) {
returnStatus = retStatus;
setVisible (false);
dispose ();
}

/**
* @param args the command line arguments
*/

// Variables declaration - do not modify
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
// End of variables declaration

private int returnStatus = RET_CANCEL;
}

class KeyHandler extends KeyAdapter {
OutputStream os;

public KeyHandler(OutputStream os) {
super();
this.os = os;
}


public void keyTyped(KeyEvent evt) {
char newCharacter = evt.getKeyChar();
try {
os.write((int)newCharacter);
} catch (IOException e) {
System.err.println("OutputStream write error: " + e);
}
}
}
public class Serial extends java.awt.Frame implements SerialPortEventListener {

private String pname;
private CommPortIdentifier pid;
private SerialPort sport;
private OutputStream os;
private InputStream is;
private KeyHandler keyHandler;
private boolean opened=false;
/** Creates new form Frame_1 */
public Serial() {
initComponents ();
pack ();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
textArea1 = new java.awt.TextArea();
textArea3 = new java.awt.TextArea();
button1 = new java.awt.Button();
button2 = new java.awt.Button();
label1 = new java.awt.Label();
label3 = new java.awt.Label();
button3 = new java.awt.Button();
choice1= new java.awt.Choice();
setLayout(null);
setBackground(java.awt.Color.lightGray);
setSize(400,400);
// setResizable(false);
setBounds(0,0,400,400);
setTitle("Serial Data Transfer...");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
}
);

textArea1.setBackground(java.awt.Color.white);
textArea1.setName("text3");
textArea1.setFont(new java.awt.Font ("Dialog", 0, 11));
textArea1.setForeground(java.awt.Color.black);

add(textArea1);
textArea1.setBounds(20, 60, 270, 120);


textArea3.setBackground(java.awt.Color.white);
textArea3.setName("text5");
textArea3.setFont(new java.awt.Font ("Dialog", 0, 11));
textArea3.setForeground(java.awt.Color.black);
textArea1.setEditable(false);
add(textArea3);
textArea3.setBounds(20, 240, 270, 110);


button1.setFont(new java.awt.Font ("Dialog", 0, 11));
button1.setLabel("Open Port");
button1.setBackground(new java.awt.Color (236, 233, 216));
button1.setForeground(java.awt.Color.black);
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
}
);

add(button1);
button1.setBounds(320, 150, 110, 50);


button2.setFont(new java.awt.Font ("Dialog", 0, 11));
button2.setLabel("Close Port");
button2.setBackground(new java.awt.Color (236, 233, 216));
button2.setForeground(java.awt.Color.black);
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button2ActionPerformed(evt);
}
}
);

add(button2);
button2.setBounds(320, 200, 110, 50);


label1.setFont(new java.awt.Font ("Dialog", 0, 11));
label1.setName("label2");
label1.setBackground(java.awt.Color.lightGray);
label1.setForeground(java.awt.Color.black);
label1.setText("Received");

add(label1);
label1.setBounds(30, 20, 130, 30);


label3.setFont(new java.awt.Font ("Dialog", 0, 11));
label3.setName("label4");
label3.setBackground(java.awt.Color.lightGray);

label3.setForeground(java.awt.Color.black);
label3.setText("Send");

add(label3);
label3.setBounds(30, 200, 150, 30);

choice1.setFont(new java.awt.Font ("Dialog", 0, 11));
choice1.setBackground(java.awt.Color.white);
choice1.setForeground(java.awt.Color.black);

add(choice1);
choice1.setBounds(320, 100, 110, 30);


button3.setFont(new java.awt.Font ("Dialog", 0, 11));
button3.setLabel("Not Connected");
button3.setBackground(new java.awt.Color (236, 233, 216));
button3.setForeground(java.awt.Color.black);

add(button3);
button3.setBounds(320, 280, 110, 40);
addportname();

}//GEN-END:initComponents

private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed
// Add your handling code here:
closeconnection();
}//GEN-LAST:event_button2ActionPerformed

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
// Add your handling code here:
createconnection();
}//GEN-LAST:event_button1ActionPerformed

/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm

System.exit (0);
}//GEN-LAST:event_exitForm
private void closeconActionPerformed(java.awt.event.ActionEvent evt) {
// Add your handling code here:
closeconnection();
}
void createconnection(){

button3.setLabel("Connecting...");
if (opened) System.out.println("One port already opened");
else {


pname=choice1.getSelectedItem();
System.out.println("pname"+pname);

try {
pid = CommPortIdentifier.getPortIdentifier(pname);
} catch (NoSuchPortException e) {

new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot retrieve Port Identifier...").show ();
button3.setLabel("Not Connected");
System.out.println("exception");
}

try {
sport = (SerialPort)pid.open("Serial", 30000);
} catch (PortInUseException e) {
new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot open Serial Port...").show ();
button3.setLabel("Not Connected");
System.out.println("exception");
}
try {
sport.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot Set Parameters for Serial Port...").show ();
button3.setLabel("Not Connected");}
try {
os = sport.getOutputStream();
is = sport.getInputStream();
} catch (IOException e) {
new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot Initialize Input & Output stream...").show ();
button3.setLabel("Not Connected");
sport.close();
}
keyHandler = new KeyHandler(os);
textArea3.addKeyListener(keyHandler);

try {

sport.addEventListener(this);
} catch (TooManyListenersException e) {
new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot add Listener to Serial Port...").show ();
button3.setLabel("Not Connected");
sport.close();
}

sport.notifyOnDataAvailable(true);
opened=true;
button3.setLabel("Connected");
}//end else
}

void closeconnection(){
if (!(opened)) System.out.println("Port not opened");
else{
button3.setLabel("Disconnecting...");
if (sport != null) {
try {
os.close();
is.close();
button3.setLabel("Not Connected");
} catch (IOException e) {
new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot close Serial port...").show ();
System.out.println(e);
}
sport.close();
opened=false;

}
}
}
public void serialEvent(SerialPortEvent e) {
StringBuffer inputbuf = new StringBuffer();
int data = 0;
// type of event.
switch (e.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
while (data != -1) {
try {
data = is.read();
if (data == -1) {
break;
}
if ('\r' == (char)data) {
inputbuf.append('\n');
} else {
inputbuf.append((char)data);
if ('\n' == (char)data) {
textArea1.append(new String(inputbuf));
inputbuf=new StringBuffer();

}

}
} catch (IOException ex) {
new OKCancelDialog (new javax.swing.JFrame (), true,"Cannot recieve data from Serial Port...").show ();
System.out.println(ex);
return;
}
}
textArea3.append(new String(inputbuf));
break;
}
}

void addportname() {


Enumeration en = CommPortIdentifier.getPortIdentifiers();


while (en.hasMoreElements()) {
pid = (CommPortIdentifier) en.nextElement();
if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL) {
choice1.addItem(pid.getName());
}
}

}





public static void main (String args[]) {
Serial s=new Serial();//.show ();
s.setSize(500,400);
s.show();
}




// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.TextArea textArea1;
private java.awt.TextArea textArea3;
private java.awt.Button button1;
private java.awt.Button button2;
private java.awt.Label label1;
private java.awt.Label label3;
private java.awt.Button button3;
private java.awt.Choice choice1;

// End of variables declaration//GEN-END:variables

}