java swing 串口_记录自己第一次用swing做的简易串口通信工具

本文介绍了一个使用Java Swing编写的简易串口通信工具。通过Swing组件创建用户界面,包括串口选择、波特率设置、打开和关闭串口功能。同时,工具具备发送和接收数据功能,支持ASCII和十六进制数据格式,并能实时显示串口通信日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

packagemain;importgnu.io.PortInUseException;importgnu.io.SerialPort;importjava.awt.Color;importjava.awt.EventQueue;importjava.awt.GraphicsEnvironment;importjava.awt.Image;importjava.awt.Point;importjava.awt.Toolkit;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjavax.swing.JFrame;importjavax.swing.JPanel;importjavax.swing.border.EmptyBorder;importjavax.swing.event.PopupMenuEvent;importjavax.swing.event.PopupMenuListener;importjavax.swing.text.DefaultCaret;importjavax.swing.BorderFactory;importjavax.swing.ImageIcon;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JScrollPane;importjavax.swing.JTextField;importjava.awt.SystemColor;importjava.awt.Font;importjavax.swing.JTextArea;importjava.awt.event.ActionListener;importjava.awt.event.ActionEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileWriter;importjava.io.IOException;importjava.io.StringReader;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.List;importjavax.swing.UIManager;importutils.ByteUtils;importutils.ShowUtils;importmanager.SerialPortManager;importjavax.swing.JLabel;importjavax.swing.JRadioButton;importjavax.swing.JToggleButton;public class ClientPort extendsJFrame {/****/

private static final long serialVersionUID = 1L;privateJPanel contentPane;//程序界面宽度

public final int WIDTH = 800;//程序界面高度

public final int HEIGHT = 600;//设置window的icon(自定义Windows窗口的icon图标)

Toolkit toolkit =getToolkit();

Image icon= toolkit.getImage(ClientPort.class.getResource("computer.png"));privateJTextField txtLog;//串口列表

private List CommList = null;//串口对象

privateSerialPort Serialport;private JComboBox commChoice = new JComboBox();private JButton openportButton = new JButton("打开串口");private JComboBox baudChoice = new JComboBox();private JButton sendData = new JButton("发送");private JTextArea textArea = new JTextArea();//指令显示区

private final JTextArea textArea_1 = new JTextArea();//指令发送区

private JRadioButton DataHexChoice = new JRadioButton("Hex", true);private JRadioButton DataASCIIChoice = new JRadioButton("ASCLL");private JLabel mA1 = new JLabel("", JLabel.CENTER);private JToggleButton renovate = new JToggleButton("");//刷新

/*** Launch the application.*/

public static voidmain(String[] args) {

EventQueue.invokeLater(newRunnable() {public voidrun() {try{

ClientPort frame= newClientPort();

frame.setVisible(true);

}catch(Exception e) {

e.printStackTrace();

}

}

});

}/*** Create the frame.

*

*@throwsIOException*/

public ClientPort() throwsIOException {

initView();

initData();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

contentPane= newJPanel();

contentPane.setBackground(Color.LIGHT_GRAY);

contentPane.setBorder(new EmptyBorder(5, 5, 12, 5));

setContentPane(contentPane);

contentPane.setLayout(null);//上面部分

JPanel panel = newJPanel();

panel.setForeground(SystemColor.controlHighlight);

panel.setBounds(0, 0, 794, 91);

panel.setBorder(BorderFactory.createLineBorder(Color.gray));

contentPane.add(panel);

panel.setLayout(null);//打开串口按钮

openportButton.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {if ("打开串口".equals(openportButton.getText())&& Serialport == null) {

openSerialPort(e);

}else{

closeSerialPort(e);

}

}

});

openportButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));

openportButton.setBounds(0, 0, 151, 91);

panel.add(openportButton);//查询参数按钮

JButton btnNewButton_1 = new JButton("查询参数");

btnNewButton_1.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

textArea.setText("型号:11 03 14 00 00 10 43 66" + "\r\n"

+ "名称:11 03 10 88 00 10 C2 7C");

}

});

btnNewButton_1.setFont(new Font("微软雅黑", Font.PLAIN, 12));

btnNewButton_1.setBounds(150, 0, 151, 91);

panel.add(btnNewButton_1);

JPanel panel_2= newJPanel();

panel_2.setBounds(643, 0, 151, 89);

panel.add(panel_2);

panel_2.setLayout(null);

commChoice.setBounds(64, 10, 77, 26);

commChoice.addPopupMenuListener(newPopupMenuListener() {public voidpopupMenuWillBecomeVisible(PopupMenuEvent e) {

CommList=SerialPortManager.findPorts();//检查是否有可用串口,有则加入选项中

if (CommList == null || CommList.size() < 1) {

ShowUtils.warningMessage("没有搜索到有效串口!");

}else{int index =commChoice.getSelectedIndex();

commChoice.removeAllItems();for(String s : CommList) {

commChoice.addItem(s);

}

commChoice.setSelectedIndex(index);

}

}public voidpopupMenuWillBecomeInvisible(PopupMenuEvent e) {//NO OP

}public voidpopupMenuCanceled(PopupMenuEvent e) {//NO OP

}

});

panel_2.add(commChoice);

baudChoice.setBounds(64, 46, 77, 26);

panel_2.add(baudChoice);

JLabel label= new JLabel(" 串口");

label.setFont(new Font("微软雅黑", Font.PLAIN, 12));

label.setBounds(10, 16, 54, 15);

panel_2.add(label);

JLabel label_1= new JLabel(" 波特率");

label_1.setFont(new Font("微软雅黑", Font.PLAIN, 12));

label_1.setBounds(10, 52, 54, 15);

panel_2.add(label_1);

renovate.setToolTipText("刷新数据");

renovate.setBackground(SystemColor.control);

renovate.setBounds(300, 0, 151, 91);

renovate.setContentAreaFilled(false);//图片填充

renovate.setSelectedIcon(new ImageIcon("src/Icon/renovate_on.png"));

renovate.setIcon(new ImageIcon("src/Icon/renovate_off.png"));

renovate.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

JToggleButton renovate=(JToggleButton) e.getSource();

String s1= "1103006000018684";//检测电流

if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口再操作!");return;

}if (renovate.isSelected()) {//检查是否选中该元素

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s1));

}else{

ShowUtils.warningMessage("数据刷新已关闭!");return;

}

}

});

panel.add(renovate);//右部分

JPanel panel_r = newJPanel();

panel_r.setBackground(Color.WHITE);

panel_r.setForeground(Color.BLACK);

panel_r.setBounds(557, 91, 237, 345);

panel_r.setBorder(BorderFactory.createLineBorder(Color.white));

contentPane.add(panel_r);

panel_r.setLayout(null);//Log区

txtLog = newJTextField();

txtLog.setFont(new Font("微软雅黑", Font.PLAIN, 12));

txtLog.setBackground(SystemColor.controlHighlight);

txtLog.setText("Log");

txtLog.setBounds(0, 0, 237, 21);

txtLog.setEditable(false);//Log后面禁止输入字符

panel_r.add(txtLog);

txtLog.setColumns(10);

textArea.setFont(new Font("微软雅黑", Font.PLAIN, 13));//指令显示区

textArea.setBounds(1, 1, 235, 344);

textArea.setFocusable(false);

textArea.setLineWrap(true);//自动换行

panel_r.add(textArea);//滚动条

JScrollPane scrollPane = newJScrollPane(textArea);

scrollPane.setBounds(0, 21, 237, 324);

scrollPane

.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);//垂直滚动条自动出现

DefaultCaret caret =(DefaultCaret) textArea.getCaret();

caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);//滚动条随文字刷新在下方显示

panel_r.add(scrollPane);//左部分

JPanel panel_l = newJPanel();

panel_l.setBackground(SystemColor.control);

panel_l.setBounds(0, 91, 554, 481);

panel_l.setBorder(BorderFactory.createLineBorder(Color.white));

contentPane.add(panel_l);

panel_l.setLayout(null);

JToggleButton DO_1= new JToggleButton("");

DO_1.setToolTipText("DO-1");

DO_1.setBackground(SystemColor.control);

DO_1.setBounds(39, 42, 75, 40);

DO_1.setBorderPainted(false);//取消边框

DO_1.setContentAreaFilled(false);//图片填充

DO_1.setSelectedIcon(new ImageIcon("src/Icon/on.png"));

DO_1.setIcon(new ImageIcon("src/Icon/off.png"));

DO_1.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

JToggleButton DO_1=(JToggleButton) e.getSource();

String s1= "11050000FF008EAA";//DO-1开

String s2 = "110500000000CF5A";//DO-1关//String data = textArea.getText().toString();

/** if (toggleBtn.isSelected()) { textArea_1.setText(s1); }else {

* textArea_1.setText(s2); }*/

if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口再操作!");return;

}if(DO_1.isSelected()) {

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s1));

}else{

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s2));

}

}

});

panel_l.add(DO_1);

JToggleButton DO_2= new JToggleButton("");

DO_2.setToolTipText("DO-2");

DO_2.setContentAreaFilled(false);

DO_2.setBorderPainted(false);

DO_2.setBackground(SystemColor.menu);

DO_2.setBounds(166, 42, 75, 40);

DO_2.setSelectedIcon(new ImageIcon("src/Icon/on.png"));

DO_2.setIcon(new ImageIcon("src/Icon/off.png"));

DO_2.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

JToggleButton DO_2=(JToggleButton) e.getSource();

String s1= "11050001FF00DF6A";//DO-2开

String s2 = "1105000100009E9A";//DO-2关

if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口再操作!");return;

}if(DO_2.isSelected()) {

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s1));

}else{

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s2));

}

}

});

panel_l.add(DO_2);

JLabel lblNewLabel= new JLabel("DO-1");

lblNewLabel.setBounds(65, 17, 30, 15);

panel_l.add(lblNewLabel);

JLabel lblDo= new JLabel("DO-2");

lblDo.setBounds(192, 17, 30, 15);

panel_l.add(lblDo);

JToggleButton DO_3= new JToggleButton("");

DO_3.setToolTipText("DO-3");

DO_3.setContentAreaFilled(false);

DO_3.setBorderPainted(false);

DO_3.setBackground(SystemColor.menu);

DO_3.setBounds(302, 42, 75, 40);

DO_3.setSelectedIcon(new ImageIcon("src/Icon/on.png"));

DO_3.setIcon(new ImageIcon("src/Icon/off.png"));

DO_3.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

JToggleButton DO_3=(JToggleButton) e.getSource();

String s1= "11050002FF002F6A";//DO_3开

String s2 = "1105000200006E9A";//DO_3关

if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口再操作!");return;

}if(DO_3.isSelected()) {

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s1));

}else{

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s2));

}

}

});

panel_l.add(DO_3);

JLabel lblDo_1= new JLabel("DO-3");

lblDo_1.setBounds(329, 17, 30, 15);

panel_l.add(lblDo_1);

JToggleButton DO_4= new JToggleButton("");

DO_4.setToolTipText("DO-4");

DO_4.setContentAreaFilled(false);

DO_4.setBorderPainted(false);

DO_4.setBackground(SystemColor.menu);

DO_4.setBounds(436, 42, 75, 40);

DO_4.setSelectedIcon(new ImageIcon("src/Icon/on.png"));

DO_4.setIcon(new ImageIcon("src/Icon/off.png"));

DO_4.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

JToggleButton DO_4=(JToggleButton) e.getSource();

String s1= "11050003FF007EAA";//DO_4开

String s2 = "1105000300003F5A";//DO_4关

if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口再操作!");return;

}if(DO_4.isSelected()) {

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s1));

}else{

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(s2));

}

}

});

panel_l.add(DO_4);

JLabel lblDo_2= new JLabel("DO-4");

lblDo_2.setBounds(459, 17, 30, 15);

panel_l.add(lblDo_2);

JPanel dial_1= newJPanel();

dial_1.setBounds(39, 110, 180, 148);

dial_1.setBorder(BorderFactory.createLoweredBevelBorder());

panel_l.add(dial_1);

dial_1.setLayout(null);

mA1.setBounds(33, 111, 116, 27);

dial_1.add(mA1);

JLabel lblNewLabel_2= new JLabel("电流(mA)", JLabel.CENTER);

lblNewLabel_2.setBounds(62, 89, 60, 22);

dial_1.add(lblNewLabel_2);

JPanel dial_2= newJPanel();

dial_2.setBorder(BorderFactory.createLoweredBevelBorder());

dial_2.setBounds(309, 110, 180, 148);

panel_l.add(dial_2);

dial_2.setLayout(null);

JPanel dial_3= newJPanel();

dial_3.setBorder(BorderFactory.createLoweredBevelBorder());

dial_3.setBounds(39, 303, 180, 148);

panel_l.add(dial_3);

dial_3.setLayout(null);

JPanel dial_4= newJPanel();

dial_4.setBorder(BorderFactory.createLoweredBevelBorder());

dial_4.setBounds(309, 303, 180, 148);

panel_l.add(dial_4);

dial_4.setLayout(null);

JPanel panel_1= newJPanel();

panel_1.setBackground(UIManager.getColor("CheckBox.background"));

panel_1.setBounds(557, 437, 237, 135);

contentPane.add(panel_1);

panel_1.setLayout(null);

textArea_1.setBounds(0, 0, 237, 97);

textArea_1.setLineWrap(true);//自动换行

panel_1.add(textArea_1);

sendData.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

sendData(e);

}

});

sendData.setBounds(0, 97, 84, 38);

panel_1.add(sendData);

JButton button_1= new JButton("清空");

button_1.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {//清空文本输入区

textArea_1.setText("");

}

});

button_1.setBounds(153, 97, 84, 38);

panel_1.add(button_1);

DataHexChoice.setBounds(82, 97, 66, 17);

panel_1.add(DataHexChoice);

DataASCIIChoice.setBounds(82, 118, 66, 17);

panel_1.add(DataASCIIChoice);

}/*** 初始化窗口*/

private voidinitView() {//禁止窗口最大化

setResizable(false);//设置icon

setIconImage(icon);//设置程序窗口居中显示

Point p =GraphicsEnvironment.getLocalGraphicsEnvironment()

.getCenterPoint();

setBounds(p.x- WIDTH / 2, p.y - HEIGHT / 2, WIDTH, HEIGHT);

getContentPane().setLayout(null);

setTitle("串口通信");

addWindowListener(newWindowAdapter() {//添加对窗口状态的监听

public voidwindowClosing(WindowEvent arg0) {//当窗口关闭时

System.exit(0); //退出程序

}

});

}/*** 初始化数据*/

private voidinitData() {

CommList=SerialPortManager.findPorts();//检查是否有可用串口,有则加入选项中

if (CommList == null || CommList.size() < 1) {

ShowUtils.warningMessage("没有搜索到有效串口!");

}else{for(String s : CommList) {

commChoice.addItem(s);

}

}

baudChoice.addItem("9600");

baudChoice.addItem("19200");

baudChoice.addItem("38400");

baudChoice.addItem("57600");

baudChoice.addItem("115200");

}/*** 打开串口

*

*@paramevt

* 点击事件*/

private voidopenSerialPort(java.awt.event.ActionEvent evt) {//获取串口名称

String commName =(String) commChoice.getSelectedItem();//获取波特率,默认为9600

int baudrate = 9600;

String bps=(String) baudChoice.getSelectedItem();

baudrate=Integer.parseInt(bps);//检查串口名称是否获取正确

if (commName == null || commName.equals("")) {

ShowUtils.warningMessage("没有搜索到有效串口!");

}else{try{

Serialport=SerialPortManager

.openPort(commName, baudrate, bps);if (Serialport != null) {

textArea.setText("串口已打开" + "\r\n");

openportButton.setText("关闭串口");

}

}catch(PortInUseException e) {

ShowUtils.warningMessage("串口已被占用!");

}

}//添加串口监听

SerialPortManager.addListener(Serialport,newSerialPortManager.DataAvailableListener() {public voiddataAvailable() {byte[] data = null;try{if (Serialport == null) {

ShowUtils.errorMessage("串口对象为空,监听失败!");

}else{//读取串口数据

data =SerialPortManager.readFromPort(Serialport);

logFile();//以十六进制的形式接收数据

if(DataHexChoice.isSelected()) {

textArea.append(ByteUtils

.byteArrayToHexString(data)+ "\r\n");

electricity();

}//以字符串的形式接收数据

if(DataASCIIChoice.isSelected()) {

textArea.append(new String(data) + "\r\n");

}

}

}catch(Exception e) {

ShowUtils.errorMessage(e.toString());//发生读取错误时显示错误信息后退出系统

System.exit(0);

}

}

});

}/*** 关闭串口

*

*@paramevt

* 点击事件*/

private voidcloseSerialPort(java.awt.event.ActionEvent evt) {

SerialPortManager.closePort(Serialport);

textArea.setText("串口已关闭" + "\r\n");

openportButton.setText("打开串口");

Serialport= null;

}/*** 发送数据

*

*@paramevt

* 点击事件*/

private voidsendData(java.awt.event.ActionEvent evt) {//待发送数据

String data =textArea_1.getText().toString();if (Serialport == null) {

ShowUtils.warningMessage("请先打开串口!");return;

}if ("".equals(data) || data == null) {

ShowUtils.warningMessage("请输入要发送的数据!");return;

}//以十六进制的形式发送数据

if(DataHexChoice.isSelected()) {

SerialPortManager.sendToPort(Serialport,

ByteUtils.hexStr2Byte(data));

}//以字符串的形式发送数据

if(DataASCIIChoice.isSelected()) {

SerialPortManager.sendToPort(Serialport, data.getBytes());

}

}/*** 接收电流数据

*

*@throwsIOException

**/

private void electricity() throwsIOException {

String s1= "1103006000018684";//检测电流

if(renovate.isSelected()) {

SerialPortManager.sendToPort(Serialport, ByteUtils.hexStr2Byte(s1));

BufferedReader br= new BufferedReader(newStringReader(textArea

.getText().toString()));

String result= null;

String line=br.readLine();

String mAdata;while ((line = br.readLine()) != null) {

result=line;

}

br.close();

mAdata= result.substring(6, 10);

String str= Integer.valueOf(mAdata, 16).toString();double a =Integer.parseInt(str);double b = a / 1000;

String s=String.valueOf(b);

mA1.setText(s);

}

}/*** 写入Log*/

private void logFile() throwsIOException {

FileWriter fWriter= newFileWriter("D:/workspace/SerialDemo/logFile.txt");

BufferedWriter bWriter= newBufferedWriter(fWriter);

String log=textArea.getText().toString();

Date dNow= newDate();

SimpleDateFormat ft= new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");

bWriter.write(ft.format(dNow)+log);

bWriter.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值