下载javax.comm包后才能使用这些类。
// 功能:从串行口COM4中接收数据
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import javax.comm.*;
import javax.swing.JFrame;
public class SimpleReadForm extends JFrame implements Runnable, SerialPortEventListener {
public SimpleReadForm() {
initComponents();
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
messageText = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
OpenButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
recText = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("收到的数据:");
OpenButton.setText("打开串口");
OpenButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenButtonActionPerformed(evt);
}
});
recText.setColumns(20);
recText.setRows(5);
jScrollPane1.setViewportView(recText);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(OpenButton)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addContainerGap(269, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(messageText, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(messageText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(OpenButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void OpenButtonActionPerformed(java.awt.event.ActionEvent evt) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM3")) { //端口名
try {
serialPort = (SerialPort) portId.open("ReadComm", 2000);
messageText.setText("已打开端口COM3 ,正在接收数据..... ");
} catch (PortInUseException e) {
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
}
serialPort.notifyOnDataAvailable(true);
} //if end
} //if end
} //while end
readThread = new Thread(this);
readThread.start(); //线程负责每接收一次数据休眠20秒钟
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SimpleReadForm().setVisible(true);
}
});
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
}
} //run() end
public void serialEvent(SerialPortEvent event) {
try {
serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
byte[] readBuffer = new byte[20];
int numBytes=0;
String readStr="";
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
}
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
} //while end
str = new String(readBuffer);
for(int iii=0;iii<numBytes;iii++){
readStr=readStr + Byte.toString(readBuffer[iii]);
}
recText.append(str + "\n");
recText.append(readStr+"\n");
} catch (IOException e) {
}
}
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
String str = "";
// Variables declaration - do not modify
private javax.swing.JButton OpenButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField messageText;
private javax.swing.JTextArea recText;
// End of variables declaration
}
PS:很奇怪,第一天调试的时候就是一直没出来,程序就是一直找不到串口,hasMoreElements()一直显示为false。第二天一打开就成功了。后来想了想,原因不外乎有二:一、那天刚安装了USB转串口的驱动,需要JVM找到串口的话也许需要重新启动电脑。二、RP问题。(Orz,其实还是不知道为什么,程序有时候就是这样犯贱。。。)