1.下载jar包
RXTXcomm.jar
2.实现代码
package main; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JTextField; import gnu.io.*; import main.*; import resources.HardWareProperties; import javax.swing.JButton; class R_Frame extends JDialog implements Runnable, SerialPortEventListener { /* 检测系统中可用的通讯端口类 */ static CommPortIdentifier portId; /* Enumeration 为枚举型类,在java.util中 */ static Enumeration portList; InputStream inputStream; /* 声明RS-232串行端口的成员变量 */ SerialPort serialPort; Thread readThread; byte[] readBuffer =new byte[2000]; public String str = ""; TextField out_message = new TextField("上面文本框显示接收到的数据"); TextArea in_message = new TextArea(); static R_Frame R_win = null; public static void main(String[] args) throws IOException { if (R_win == null) { /* 实例化接收串口数据的窗体类 */ R_win = new R_Frame(); /* 定义窗体适配器的关闭按钮功能 */ ViewUtils.showCentre(R_win); R_win.setAlwaysOnTop(true); R_win.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { R_win.serialPort.removeEventListener(); R_win.serialPort.close(); ViewUtils.closeWarn(R_win); R_win = null; } }); } else { R_win.setVisible(true); R_win.setAlwaysOnTop(true); R_win.in_message.setText(""); } } /* 建立窗体 */ R_Frame() throws IOException { setSize(327, 315); setVisible(true); try { actionPerformed(); } catch (UnsupportedCommOperationException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } in_message.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { // InputEvent.listenEnterKeyToAnyInput(text_certificate, // lblNewLabel_2); serialPort.removeEventListener(); serialPort.close(); dispose(); } } }); this.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) {// 失去焦点时 setVisible(true); } public void focusGained(FocusEvent e) {// 获得焦点时 } }); getContentPane().add(out_message, "South"); in_message.setEditable(false); getContentPane().add(in_message, "Center"); JButton btnNewButton = new JButton("u624Bu52A8u8BFBu53D6"); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // 向端口写数据 OutputStream out; try { out = serialPort.getOutputStream(); out.write("Q<CR>".getBytes()); //out.write("Q<CR><LF>".getBytes()); out.flush(); JOptionPane.showMessageDialog(null, "读取成功!", "错误提示!", JOptionPane.ERROR_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "读取失败!", "错误提示!", JOptionPane.ERROR_MESSAGE); } } }); getContentPane().add(btnNewButton, BorderLayout.WEST); } // R_Frame() end /* 点击按扭所触发的事件:打开串口,并监听串口. */ public void actionPerformed() throws IOException, UnsupportedCommOperationException { /* 获取系统中所有的通讯端口 */ portList = CommPortIdentifier.getPortIdentifiers(); /* 用循环结构找出串口 */ while (portList.hasMoreElements()) { /* 强制转换为通讯端口类型 */ portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals(HardWareProperties.COM)) { try { serialPort = (SerialPort) portId.open("ReadComm", 1000); out_message.setText("正在读取数据..... "); } catch (PortInUseException e) { JOptionPane.showMessageDialog(null, "打开串口出错!", "错误提示!", JOptionPane.ERROR_MESSAGE); } /* 设置串口监听器 */ try { serialPort.setSerialPortParams(Integer.parseInt(HardWareProperties.HZ), Integer.parseInt(HardWareProperties.LENGTH), Integer.parseInt(HardWareProperties.SDOPSIZE), Integer.parseInt(HardWareProperties.CHECK)); serialPort.setRTS(true); serialPort.setDTR(true); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); // SendThread sendThread= new SendThread(); // sendThread.serialPort=serialPort; // sendThread.start(); // ReadThread readThread=new ReadThread(); // readThread.serialPort=serialPort; // readThread.in_message=in_message; // readThread.start(); // Read(); } catch (TooManyListenersException e) { JOptionPane.showMessageDialog(null, "监听出错!", "错误提示!", JOptionPane.ERROR_MESSAGE); } /* 侦听到串口有数据,触发串口事件 */ // serialPort.notifyOnDataAvailable(true); } // if end } // if end } // while end readThread = new Thread(this); readThread.start(); // 线程负责每接收一次数据休眠20秒钟 } // actionPerformed() end /* 接收数据后休眠0.2秒钟 */ public void run() { } // run() end @Override /* 串口监听器触发的事件,设置串口通讯参数,读取数据并写到文本区中 */ public void serialEvent(SerialPortEvent event) { try { Read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // serialEvent() end public void Read() throws IOException { byte[] readBuffer = new byte[128]; // try { // Thread.sleep(5000); // } catch (InterruptedException e1) { // e1.printStackTrace(); // } try { inputStream = serialPort.getInputStream(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "打开流出错!", "错误提示!", JOptionPane.ERROR_MESSAGE); } int numBytes=0; try { /* 从线路上读取数据流 */ while (inputStream.available() > 0) { try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } numBytes = inputStream.read(readBuffer); } // while end String str1 = new String(readBuffer); StringBuffer str2 = new StringBuffer(); str2.append(str1); str2.append("读入位流数:"+numBytes); in_message.setText("读入位流数:"+numBytes+str2.toString()); inputStream.close(); /* 接收到的数据存放到文本区中 */ // if(str1.contains(" ") || str1.contains(" ") || str1.contains(" ") || str1.contains(" ")){ // String[] strs = str.split(","); // str+=str1; // in_message.setText(str); // // str=""; // } // else { // str+=str1; // JOptionPane.showMessageDialog(null, "包头:"+str1, "有数据到了!", JOptionPane.ERROR_MESSAGE); // } // in_message.setText(str); //for (int i = 0; i < str.length(); i++) { // if(str.substring(i, 1)==" ") // { // in_message.setText(str.substring(0,i)); // str=str.substring(i+1); // break; // } //} // 向端口写数据 // OutputStream out = serialPort.getOutputStream(); // out.write(str.getBytes()); // out.flush(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "读流出错!", "错误提示!", JOptionPane.ERROR_MESSAGE); } } } // 类R_Frame end