java串口通讯带UI界面

ゝ一纸荒年。 2022-07-30 15:25 279阅读 0赞
  1. package com.jetf.serialport;
  2. import gnu.io.CommPortIdentifier;
  3. import gnu.io.NoSuchPortException;
  4. import gnu.io.PortInUseException;
  5. import gnu.io.SerialPort;
  6. import gnu.io.SerialPortEvent;
  7. import gnu.io.SerialPortEventListener;
  8. import gnu.io.UnsupportedCommOperationException;
  9. import java.awt.BorderLayout;
  10. import java.awt.Button;
  11. import java.awt.Color;
  12. import java.awt.Font;
  13. import java.awt.GridLayout;
  14. import java.awt.Image;
  15. import java.awt.TextArea;
  16. import java.awt.TextField;
  17. import java.awt.event.ActionEvent;
  18. import java.awt.event.ActionListener;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.ArrayList;
  23. import java.util.Enumeration;
  24. import java.util.List;
  25. import java.util.TooManyListenersException;
  26. import javax.imageio.ImageIO;
  27. import javax.swing.JComboBox;
  28. import javax.swing.JFrame;
  29. import javax.swing.JLabel;
  30. import javax.swing.JOptionPane;
  31. import javax.swing.JPanel;
  32. import javax.swing.SwingConstants;
  33. import javax.swing.border.EmptyBorder;
  34. public class JavaRs232 extends JFrame implements ActionListener,
  35. SerialPortEventListener {
  36. /**
  37. * JDK Serial Version UID
  38. */
  39. private static final long serialVersionUID = -7270865686330790103L;
  40. protected int WIN_WIDTH = 380;
  41. protected int WIN_HEIGHT = 300;
  42. private JComboBox portCombox, rateCombox, dataCombox, stopCombox,
  43. parityCombox;
  44. private Button openPortBtn, closePortBtn, sendMsgBtn;
  45. private TextField sendTf;
  46. private TextArea readTa;
  47. private JLabel statusLb;
  48. private String portname, rate, data, stop, parity;
  49. protected CommPortIdentifier portId;
  50. protected Enumeration<?> ports;
  51. protected List<String> portList;
  52. protected SerialPort serialPort;
  53. protected OutputStream outputStream = null;
  54. protected InputStream inputStream = null;
  55. protected String mesg;
  56. protected int sendCount, reciveCount;
  57. /**
  58. * 默认构造函数
  59. */
  60. public JavaRs232() {
  61. super("Java RS-232串口通信测试程序 凡梦星尘");
  62. setSize(WIN_WIDTH, WIN_HEIGHT);
  63. setLocationRelativeTo(null);
  64. Image icon = null;
  65. try {
  66. icon = ImageIO.read(JavaRs232.class
  67. .getResourceAsStream("rs232.png"));
  68. } catch (IOException e) {
  69. showErrMesgbox(e.getMessage());
  70. }
  71. setIconImage(icon);
  72. setResizable(false);
  73. scanPorts();
  74. initComponents();
  75. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  76. setVisible(true);
  77. }
  78. /**
  79. * 初始化各UI组件
  80. *
  81. * @since 2012-3-22 下午11:56:39
  82. */
  83. public void initComponents() {
  84. // 共用常量
  85. Font lbFont = new Font("微软雅黑", Font.TRUETYPE_FONT, 14);
  86. // 创建左边面板
  87. JPanel northPane = new JPanel();
  88. northPane.setLayout(new GridLayout(1, 1));
  89. // 设置左边面板各组件
  90. JPanel leftPane = new JPanel();
  91. leftPane.setOpaque(false);
  92. leftPane.setLayout(new GridLayout(3, 2));
  93. JLabel portnameLb = new JLabel("串口号:");
  94. portnameLb.setFont(lbFont);
  95. portnameLb.setHorizontalAlignment(SwingConstants.RIGHT);
  96. portCombox = new JComboBox((String[]) portList.toArray(new String[0]));
  97. portCombox.addActionListener(this);
  98. JLabel databitsLb = new JLabel("数据位:");
  99. databitsLb.setFont(lbFont);
  100. databitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
  101. dataCombox = new JComboBox(new Integer[] { 5, 6, 7, 8 });
  102. dataCombox.setSelectedIndex(3);
  103. dataCombox.addActionListener(this);
  104. JLabel parityLb = new JLabel("校验位:");
  105. parityLb.setFont(lbFont);
  106. parityLb.setHorizontalAlignment(SwingConstants.RIGHT);
  107. parityCombox = new JComboBox(new String[] { "NONE", "ODD", "EVEN",
  108. "MARK", "SPACE" });
  109. parityCombox.addActionListener(this);
  110. // 添加组件至面板
  111. leftPane.add(portnameLb);
  112. leftPane.add(portCombox);
  113. leftPane.add(databitsLb);
  114. leftPane.add(dataCombox);
  115. leftPane.add(parityLb);
  116. leftPane.add(parityCombox);
  117. // 创建右边面板
  118. JPanel rightPane = new JPanel();
  119. rightPane.setLayout(new GridLayout(3, 2));
  120. // 设置右边面板各组件
  121. JLabel baudrateLb = new JLabel("波特率:");
  122. baudrateLb.setFont(lbFont);
  123. baudrateLb.setHorizontalAlignment(SwingConstants.RIGHT);
  124. rateCombox = new JComboBox(new Integer[] { 2400, 4800, 9600, 14400,
  125. 19200, 38400, 56000 });
  126. rateCombox.setSelectedIndex(2);
  127. rateCombox.addActionListener(this);
  128. JLabel stopbitsLb = new JLabel("停止位:");
  129. stopbitsLb.setFont(lbFont);
  130. stopbitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
  131. stopCombox = new JComboBox(new String[] { "1", "2", "1.5" });
  132. stopCombox.addActionListener(this);
  133. openPortBtn = new Button("打开端口");
  134. openPortBtn.addActionListener(this);
  135. closePortBtn = new Button("关闭端口");
  136. closePortBtn.addActionListener(this);
  137. // 添加组件至面板
  138. rightPane.add(baudrateLb);
  139. rightPane.add(rateCombox);
  140. rightPane.add(stopbitsLb);
  141. rightPane.add(stopCombox);
  142. rightPane.add(openPortBtn);
  143. rightPane.add(closePortBtn);
  144. // 将左右面板组合添加到北边的面板
  145. northPane.add(leftPane);
  146. northPane.add(rightPane);
  147. // 创建中间面板
  148. JPanel centerPane = new JPanel();
  149. // 设置中间面板各组件
  150. sendTf = new TextField(42);
  151. readTa = new TextArea(8, 50);
  152. readTa.setEditable(false);
  153. readTa.setBackground(new Color(225, 242, 250));
  154. centerPane.add(sendTf);
  155. sendMsgBtn = new Button(" 发送 ");
  156. sendMsgBtn.addActionListener(this);
  157. // 添加组件至面板
  158. centerPane.add(sendTf);
  159. centerPane.add(sendMsgBtn);
  160. centerPane.add(readTa);
  161. // 设置南边组件
  162. statusLb = new JLabel();
  163. statusLb.setText(initStatus());
  164. statusLb.setOpaque(true);
  165. // 获取主窗体的容器,并将以上三面板以北、中、南的布局整合
  166. JPanel contentPane = (JPanel) getContentPane();
  167. contentPane.setLayout(new BorderLayout());
  168. contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
  169. contentPane.setOpaque(false);
  170. contentPane.add(northPane, BorderLayout.NORTH);
  171. contentPane.add(centerPane, BorderLayout.CENTER);
  172. contentPane.add(statusLb, BorderLayout.SOUTH);
  173. }
  174. /**
  175. * 初始化状态标签显示文本
  176. *
  177. * @return String
  178. * @since 2012-3-23 上午12:01:53
  179. */
  180. public String initStatus() {
  181. portname = portCombox.getSelectedItem().toString();
  182. rate = rateCombox.getSelectedItem().toString();
  183. data = dataCombox.getSelectedItem().toString();
  184. stop = stopCombox.getSelectedItem().toString();
  185. parity = parityCombox.getSelectedItem().toString();
  186. StringBuffer str = new StringBuffer("当前串口号:");
  187. str.append(portname).append(" 波特率:");
  188. str.append(rate).append(" 数据位:");
  189. str.append(data).append(" 停止位:");
  190. str.append(stop).append(" 校验位:");
  191. str.append(parity);
  192. return str.toString();
  193. }
  194. /**
  195. * 扫描本机的所有COM端口
  196. *
  197. * @since 2012-3-23 上午12:02:42
  198. */
  199. public void scanPorts() {
  200. portList = new ArrayList<String>();
  201. Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();
  202. CommPortIdentifier portId;
  203. while (en.hasMoreElements()) {
  204. portId = (CommPortIdentifier) en.nextElement();
  205. if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
  206. String name = portId.getName();
  207. if (!portList.contains(name)) {
  208. portList.add(name);
  209. }
  210. }
  211. }
  212. if (null == portList || portList.isEmpty()) {
  213. showErrMesgbox("未找到可用的串行端口号,程序无法启动!");
  214. System.exit(0);
  215. }
  216. }
  217. /**
  218. * 打开串行端口
  219. *
  220. * @since 2012-3-23 上午12:03:07
  221. */
  222. public void openSerialPort() {
  223. // 获取要打开的端口
  224. try {
  225. portId = CommPortIdentifier.getPortIdentifier(portname);
  226. } catch (NoSuchPortException e) {
  227. showErrMesgbox("抱歉,没有找到" + portname + "串行端口号!");
  228. setComponentsEnabled(true);
  229. return;
  230. }
  231. // 打开端口
  232. try {
  233. serialPort = (SerialPort) portId.open("JavaRs232", 2000);
  234. statusLb.setText(portname + "串口已经打开!");
  235. } catch (PortInUseException e) {
  236. showErrMesgbox(portname + "端口已被占用,请检查!");
  237. setComponentsEnabled(true);
  238. return;
  239. }
  240. // 设置端口参数
  241. try {
  242. int rate = Integer.parseInt(this.rate);
  243. int data = Integer.parseInt(this.data);
  244. int stop = stopCombox.getSelectedIndex() + 1;
  245. int parity = parityCombox.getSelectedIndex();
  246. System.out.println("rate:"+rate);
  247. System.out.println("data:"+data);
  248. System.out.println("stop:"+stop);
  249. System.out.println("parity:"+parity);
  250. serialPort.setSerialPortParams(rate, data, stop, parity);
  251. } catch (UnsupportedCommOperationException e) {
  252. showErrMesgbox(e.getMessage());
  253. }
  254. // 打开端口的IO流管道
  255. try {
  256. outputStream = serialPort.getOutputStream();
  257. inputStream = serialPort.getInputStream();
  258. } catch (IOException e) {
  259. showErrMesgbox(e.getMessage());
  260. }
  261. // 给端口添加监听器
  262. try {
  263. serialPort.addEventListener(this);
  264. } catch (TooManyListenersException e) {
  265. showErrMesgbox(e.getMessage());
  266. }
  267. serialPort.notifyOnDataAvailable(true);
  268. }
  269. /**
  270. * 给串行端口发送数据
  271. *
  272. * @since 2012-3-23 上午12:05:00
  273. */
  274. public void sendDataToSeriaPort() {
  275. try {
  276. sendCount++;
  277. outputStream.write(mesg.getBytes());
  278. outputStream.flush();
  279. } catch (IOException e) {
  280. showErrMesgbox(e.getMessage());
  281. }
  282. statusLb.setText(" 发送: " + sendCount
  283. + " 接收: " + reciveCount);
  284. }
  285. /**
  286. * 关闭串行端口
  287. *
  288. * @since 2012-3-23 上午12:05:28
  289. */
  290. public void closeSerialPort() {
  291. try {
  292. if (outputStream != null)
  293. outputStream.close();
  294. if (serialPort != null)
  295. serialPort.close();
  296. serialPort = null;
  297. statusLb.setText(portname + "串口已经关闭!");
  298. sendCount = 0;
  299. reciveCount = 0;
  300. sendTf.setText("");
  301. readTa.setText("");
  302. } catch (Exception e) {
  303. showErrMesgbox(e.getMessage());
  304. }
  305. }
  306. /**
  307. * 显示错误或警告信息
  308. *
  309. * @param msg
  310. * 信息
  311. * @since 2012-3-23 上午12:05:47
  312. */
  313. public void showErrMesgbox(String msg) {
  314. JOptionPane.showMessageDialog(this, msg);
  315. }
  316. /**
  317. * 各组件行为事件监听
  318. */
  319. public void actionPerformed(ActionEvent e) {
  320. if (e.getSource() == portCombox || e.getSource() == rateCombox
  321. || e.getSource() == dataCombox || e.getSource() == stopCombox
  322. || e.getSource() == parityCombox) {
  323. statusLb.setText(initStatus());
  324. }
  325. if (e.getSource() == openPortBtn) {
  326. setComponentsEnabled(false);
  327. openSerialPort();
  328. }
  329. if (e.getSource() == closePortBtn) {
  330. if (serialPort != null) {
  331. closeSerialPort();
  332. }
  333. setComponentsEnabled(true);
  334. }
  335. if (e.getSource() == sendMsgBtn) {
  336. if (serialPort == null) {
  337. showErrMesgbox("请先打开串行端口!");
  338. return;
  339. }
  340. mesg = sendTf.getText();
  341. if (null == mesg || mesg.isEmpty()) {
  342. showErrMesgbox("请输入你要发送的内容!");
  343. return;
  344. }
  345. sendDataToSeriaPort();
  346. }
  347. }
  348. /**
  349. * 端口事件监听
  350. */
  351. public void serialEvent(SerialPortEvent event) {
  352. switch (event.getEventType()) {
  353. case SerialPortEvent.BI:
  354. case SerialPortEvent.OE:
  355. case SerialPortEvent.FE:
  356. case SerialPortEvent.PE:
  357. case SerialPortEvent.CD:
  358. case SerialPortEvent.CTS:
  359. case SerialPortEvent.DSR:
  360. case SerialPortEvent.RI:
  361. case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
  362. break;
  363. case SerialPortEvent.DATA_AVAILABLE:
  364. byte[] readBuffer = new byte[50];
  365. try {
  366. while (inputStream.available() > 0) {
  367. inputStream.read(readBuffer);
  368. }
  369. StringBuilder receivedMsg = new StringBuilder("/-- ");
  370. receivedMsg.append(new String(readBuffer).trim()).append(
  371. " --/\n");
  372. readTa.append(receivedMsg.toString());
  373. reciveCount++;
  374. statusLb.setText(" 发送: " + sendCount
  375. + " 接收: "
  376. + reciveCount);
  377. } catch (IOException e) {
  378. showErrMesgbox(e.getMessage());
  379. }
  380. }
  381. }
  382. /**
  383. * 设置各组件的开关状态
  384. *
  385. * @param enabled
  386. * 状态
  387. * @since 2012-3-23 上午12:06:24
  388. */
  389. public void setComponentsEnabled(boolean enabled) {
  390. openPortBtn.setEnabled(enabled);
  391. openPortBtn.setEnabled(enabled);
  392. portCombox.setEnabled(enabled);
  393. rateCombox.setEnabled(enabled);
  394. dataCombox.setEnabled(enabled);
  395. stopCombox.setEnabled(enabled);
  396. parityCombox.setEnabled(enabled);
  397. }
  398. /**
  399. * 运行主函数
  400. *
  401. * @param args
  402. * @since 2012-3-23 上午12:06:45
  403. */
  404. public static void main(String[] args) {
  405. new JavaRs232();
  406. }
  407. }

另注配置:

将javacomm20-win32 .zip下载的文件解压缩后,在\javacomm20-win32\commapi目录下有必需的三个文件:

comm.jar,javax.comm. properties和win32comm.dll。

将文件comm.jar拷贝到%JAVA_HOME%\jre\lib\ext;

文件 javax.comm. properties拷贝到%JAVA_HOME%\jre\lib;

文件win32comm.dll拷贝到%JAVA_HOME%\bin。

注意%JAVA_HOME%是jdk的路径,而非jre。

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读

    相关 串口通讯介绍

    串口通讯的物理连接和传输协议,是学习单片机串口编程的基础。 本文参照《深入浅出玩转51单片机》和《零死角玩转STM32》书籍,对通讯以及串口一些基本概念做了详解。 1. 串

    相关 java串口通讯实例

    现在一般的电脑都没有串口端口的了,所以还是用虚拟的串口来做测试吧。 我们用 VSPD(Virtual Serial Port Driver) 这个软件建立两个虚拟串口,COM

    相关 串口通讯之 CRC校验

    一、CRC16简介       循环冗余码CRC检验技术广泛应用于测控及通信领域。CRC计算可以靠专用的硬件来实现,但是对于低成本的微控制器系统,在没有硬件支持下实现CRC