张世豪
昨天 7be65a0428a4527889b6955c56aafdb81dda28a8
src/chuankou/SerialPortConnectionDialog.java
@@ -183,6 +183,8 @@
        exitButton.setFocusPainted(false);
        exitButton.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));
        exitButton.addActionListener(e -> {
            // 新增:退出前确保关闭串口连接
            cleanupSerialPort();
            System.exit(0);
        });
        
@@ -303,14 +305,63 @@
                        });
                        
                    } else {
                        // 连接失败处理保持不变...
                        // 连接失败
                        connectButton.setEnabled(true);
                        connectButton.setText("连接串口");
                        connectButton.setBackground(SECONDARY_COLOR);
                        statusLabel.setText("串口连接失败: " + portName);
                        showMessage("连接失败", "无法连接到串口 " + portName, "error");
                        // 关闭失败的串口连接
                        if (serialService != null) {
                            serialService.close();
                            serialService = null;
                        }
                    }
                });
                
            } catch (Exception e) {
                // 异常处理保持不变...
                SwingUtilities.invokeLater(() -> {
                    connectButton.setEnabled(true);
                    connectButton.setText("连接串口");
                    connectButton.setBackground(SECONDARY_COLOR);
                    statusLabel.setText("连接异常: " + e.getMessage());
                    showMessage("连接异常", "串口连接过程中发生错误: " + e.getMessage(), "error");
                    // 关闭异常的串口连接
                    if (serialService != null) {
                        serialService.close();
                        serialService = null;
                    }
                });
            }
        }).start();
    }
    /**
     * 新增:清理串口资源的方法
     */
    private void cleanupSerialPort() {
        if (serialService != null) {
            try {
                // 停止数据捕获
                serialService.stopCapture();
                // 停止协议解析器
                if (serialService.getProtocolParser() != null) {
                    serialService.getProtocolParser().stop();
                }
                // 关闭串口
                serialService.close();
                //System.out.println("串口连接已清理");
            } catch (Exception e) {
                System.err.println("清理串口资源时发生异常: " + e.getMessage());
            } finally {
                serialService = null;
            }
        }
    }
    
    private void showMessage(String title, String message, String type) {
@@ -351,7 +402,7 @@
    public void dispose() {
        // 如果连接失败,关闭串口
        if (!isConnected && serialService != null) {
            serialService.close();
            cleanupSerialPort();
        }
        super.dispose();
    }