최근 과정은 상단 컴퓨터를위한 직렬 통신 도구를 작성해야합니다. Java를 기반으로 한 그래픽 인터페이스와 함께 간단한 직렬 통신 도구를 작성했습니다. 이 과정은 아래에 자세히 설명되어 있습니다.^_^
하나:
우선, Java 직렬 포트 통신 작동을 지원하는 추가 JAR 패키지를 다운로드해야합니다. Java.comm은 상대적으로 오래되었으며 64 비트 시스템을 지원하지 않으므로 RXTX JAR 패키지 (32 비트/64 비트 지원)가 권장됩니다.
공식 다운로드 주소 : http://fizzed.com/oss/rxtx-for-java (참고 : FQ가 다운로드해야 할 수도 있음)
FQ가 될 수없는 어린이 신발은 여기에서 다운로드 할 수 있습니다.
http://xiazai.vevb.com/201612/yuanma/javamfzrxtx(Vevb.com).rar (32-bit)
http://xiazai.vevb.com/201612/yuanma/javamfzrxtx(Vevb.com).rar (64-bit)
둘:
압축이없는 JAR 패키지를 다운로드하여 Java 빌드 경로 아래에서 소개합니다.
포착
참고 : Java.lang.unsisfiedlinkerror 오류가 작동 중에 재배치 된 경우 rxtxparallel.dll 및 rxtxserial.dll의 두 파일을 C :/Windows/System32 디렉토리에 복사하여 오류를 해결하십시오.
삼:
이 JAR 패키지의 사용과 관련하여 SerialTool.java 클래스를 작성하여 직렬 포트 커뮤니케이션을위한 다양한 간단한 서비스를 제공합니다. 코드는 다음과 같습니다 (이 클래스는 Serialport 패키지에 있습니다) :
패키지 Serialport; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import java.util.arraylist; import java.util.enumeration; import java.util.toomanylistenersexception; import gnu.io.commport; import gnu.io. gnu.io.nosuchportexception; gnu.io.portinuseexception; import gnu.io.serialport; import gnu.io.serialporteventListener; import gnu.io.unsupportedcommoperationException; seriacleception 가져 오기;/*** Serial Port Service Class (Serial Port 및 Serial Port 및 Sending)를 제공하는 서비스를 제공합니다. 싱글 톤 디자인 모드) * @author Zhong * */public class serialTool {private static serialtool serialTool = null; static {//이 클래스가 클래스 로더로로드 될 때 SerialTool 오브젝트를 초기화합니다. if (serialTool == null) {serialTool = new SerialTool (); }} // 개인 SerialTool 클래스의 생성자는 serialTool 객체를 생성 할 수 없습니다. private serialTool () {} /*** 서비스를 제공하는 SerialTool 객체를 얻습니다* @return serialTool* /public serialTool getSerialTool () {serialTool == null) {new serialTool (new serialtool) {new SerialTool (); } return serialTool; } /*** 사용 가능한 모든 포트 찾기* @return 사용 가능한 포트 이름 목록* /public static final arraylist <straylist <string> findport () {// 현재 사용 가능한 모든 직렬 포트 열거 <commportidentifier> portlist = commportidentifier.getportidentifiers (); ArrayList <String> PortnamElist = New ArrayList <> (); // 사용 가능한 직렬 포트 이름을 추가하여 목록을 나열하고 리턴 할 while (portlist.hasmoreElements ()) {String portname = portList.nextElement (). getName (); portnamelist.add (portname); } return portnamelist; } /*** 열린 시리얼 포트* @param portname 포트 이름* @param baudrate baudrate* @return serialport 객체* @throws serialportparameterFailure를 설정하지 못했습니다. SerialPormeterFailure* @Throws NOTASERIALPORT 장치를 가리키는 포트는이 포트 장치에 해당하는 포트 장치가 없습니다. 이 포트는*/public static final serialport openport (String portname, int baudrate)가 SerialportParameterFailure, NoSuchport, nosuchport, portinuse {try {// 포트 이름 commportidentifier = commportidentifier.getPortIntifier (portname)에 의해 포트를 식별합니다. // 포트를 열고 포트 이름과 타임 아웃 (오프닝 시간)을 제공합니다 (운영 시간) Commport Commport = PortIntifier.Open (PortName, 2000); // 직렬 포트 IF (Commport instancef serialport) {Serialport Serialport = (Serialport) Commport; try {// Serial Port Serialport.setSerialportParams의 Baud rate 및 기타 매개 변수를 설정하십시오 (Baudrate, serialport.databits_8, serialport.stopbits_1, serialport.parity_none); } catch (UnsupportedCommoperationException e) {새 SerialportParameterFailure ()를 던집니다. } //system.out.println("open " + portname +"sucessly! "); 반환 시리얼 포트; } else {// Serial Port Not New NotAserialport (); }} catch (nosuchportException e1) {throw new nosuchport (); } catch (portinuseexception e2) {Throw new Portinuse (); }} / *** 직렬 포트를 닫습니다* @param serialport 닫을 직렬 포트 개체* / public static void closeport (serialport serialport) {if (serialport! = null) {serialport.close (); serialport = null; }} / *** 직렬 포트로 데이터를 보내십시오* @param serialport serialport 객체* @param 주문 데이터* @throws senddatatoserialportFailure 실패한 포트로 데이터를 보내지 못했습니다* @throws serialportOutputStreamCloseFailure Serial Port의 출력 스트림을 닫습니다. SendDatatoserialportFailure, serialportOutputStreamCloseFailure {outputStream out = null; {out = serialport.getOutputStream (); out.write (Order); out.flush (); } catch (ioException e) {새 SendDatatoserialportFailure (); } 마침내 {try {if (out! = null) {out.close (); out = null; }} catch (ioException e) {새 SerialPortOutputStreamCloseFailure (); }}} / *** 직렬 포트에서 데이터 읽기* @param serialport 연결이있는 시리얼 포트 객체가 설정되었습니다* @Throws* @throws readdatafromserialportFailure Serial Port에서 데이터를 읽는 동안 오류가 발생했습니다. @throws serialportInputsTreamCloseFailure Creep -Portport Erricport (Public Strame) [] readdatafromserialportFailure, serialportInputStreamCloseFailure {inputStream in = null; 바이트 [] bytes = null; try {in = serialport.getInputStream (); int bufflenth = in.available (); // 버퍼에서 데이터 길이를 가져옵니다. // byte 배열을 버퍼의 데이터 길이로 초기화합니다. bufflenth = in.available (); }} catch (ioexception e) {throw readdatafromserialportfailure (); } 마침내 {try {if (in! = null) {in.close (); in = null; }} catch (ioException e) {throw new serialportInputStreamCloseFailure (); }} 반환 바이트; } /*** 리스너 추가* @param 포트 직렬 포트 개체* @param 리스너 직렬 포트 리스너* @throws toomanylisteners 너무 많은 청취 클래스 객체* /public static void addlistener (Serialport port, serialporteventlistener Listener)가 TORMONYLISTENERS {// addleventlistener (surliser port.AddeventListener); // 데이터가 도착했을 때 청취 수신 스레드를 깨우라고 설정합니다. // 커뮤니케이션이 중단 될 때 인터럽트 스레드를 깨우라고 설정했습니다. } catch (toomanylistenersException e) {새로운 TOMONYLISTENERS (); }}}참고 : 이 메소드의 던지기 예외는 모두 내 사용자 지정 예외입니다. 그 이유는 주 프로그램에서 해당 처리를 용이하게하기 때문입니다. 예외 중 하나에 대한 설명은 다음과 같습니다.
(내 모든 사용자 정의 예외는 SeriaLexception 패키지에 배치됩니다)
패키지 serialexception; 공개 클래스 SerialportParameterFailure 확장 예외 { / ** * * / private static final long serialversionuid = 1L; public serialportParameterFailure () {} @override public String toString () {return "SET SERIAL PORMANTERS가 실패했습니다! 직렬 포트 작업을 열지 않습니다!"; }}각 사용자 정의 예외 클래스에 대한 toString () 메소드를 다시 작성하여 기본 프로그램이 예외를 포착 한 후 해당 오류 메시지를 인쇄 할 수 있도록했습니다.
SeriaLexception 패키지에는 수신 된 예외 객체에서 오류 정보를 추출하여 문자열로 변환하여 반환하는 클래스도 있습니다. 코드는 다음과 같습니다.
패키지 serialexception; import java.io.ioexception; import java.io.printwriter; import java.io.stringwriter;/*** 전달 된 예외에서 오류 메시지를 문자열로 추출하고 변환하는 책임; * @Author Zhong * */public class ExceptionWriter {/** * 예외에 오류 메시지를 문자열로 캡슐화하고 문자열에 캡슐화하고 문자열을 반환 * @param e 오류 예외 * @return 오류 메시지 문자열 */public static string geterRorinfofromexception (exception e) {stringwriter sw = null; 인쇄기 PW = NULL; try {sw = new StringWriter (); PW = 새로운 인쇄기 (SW); E.printstacktrace (PW); "/r/n" + sw.tostring () + "/r/n"을 반환합니다. } catch (Exception E2) {return "오류 메시지를 얻지 못했습니다. 다시 확인하고 다시 시도하십시오!"; } 마침내 {try {if (pw! = null) {pw.close (); } if (sw! = null) {sw.close (); }} catch (ioexception e1) {e1.printstacktrace (); }}}}4 :
주요 프로그램 클래스 인 Client.java의 사용에는 프로그램의 입력 주소 (기본 방법)가 포함됩니다. 기능은 환영 인터페이스를 표시하고 실제 직렬 포트 데이터 디스플레이를 위해 Dataview.java 클래스를 호출하는 것입니다.
client.java 코드는 다음과 같습니다.
패키지 Serialport; import java.awt.color; import java.awt.flowlayout; import java.awt.font; import java.awt.frame; import java.awt.graphics; import java.awt.gridlayout; import java.awt.image import java.awt.label; java.awt.toolkit; import java.awt.event.keyadapter; import java.awt.event.keyevent; import java.awt.event.windowadapter; import java.awt.event.windowevent; import javax.swing.joptionpane; exception.excemption. */public class 클라이언트 확장 프레임 {/** * */private static final long serialversionuid = 1l; / *** 프로그램 인터페이스 너비*/ public static final int 너비 = 800; / *** 프로그램 인터페이스 높이*/ public static final int height = 620; / ** * 프로그램 인터페이스의 위치 (수평 좌표) */ public static final int loc_x = 200; / ** * 프로그램 인터페이스의 위치 (수평 좌표) */ public static final int loc_y = 70; 색상 = 색상. 화이트; 이미지 오프 스크린 = null; // 이중 버퍼링에 사용 // 창의 아이콘을 설정합니다 (여기서는 Windows Window의 아이콘을 사용자 정의했습니다. Image Icon = Toolkit.getImage (client.class.getResource ( "computer.png")); // 기타 클래스를 유지합니다 DataView DataView = New Dataview (this); // 기본 인터페이스 클래스 (모니터링 데이터 표시 메인 패널 표시)/*** 메인 메소드* @param args //*/public static void main (string [] args) {new Client (). junniveFrame (); } / *** 기본 인터페이스 표시* / public void unlainframe () {this.setBounds (loc_x, loc_y, 너비, 높이); // 프로그램이 데스크탑에 나타나는 위치를 설정하십시오. // 프로그램 제목 설정 this.seticonimage (아이콘); this.setbackground (color.white); // 배경색을 설정합니다. AddWindowListener (새 WindowAdapter () {// 창 상태 추가 공개 void windowclosing (windowevent arg0) {//system.exit(0); // 프로그램 종료}); this.addkeylistener (new keymonitor ()); // 키보드 리스너를 추가 this.setResizable (false); // 창 크기를 변경할 수 없습니다. // 디스플레이 창 새 스레드 (new RepaintThread ()). start (); // Repaint Thread}/*** 프로그램 인터페이스의 다양한 구성 요소를 그립니다*/public void paint (그래픽 g) {color c = g.getColor (); g.setfont (New Font ( "Microsoft Yahei", font.bold, 40)); g.setcolor (color.black); G.DrawString ( "상부 컴퓨터의 실시간 모니터링 시스템 사용에 오신 것을 환영합니다", 45, 190); g.setfont (New Font ( "Microsoft Yahei", font.italic, 26)); g.setcolor (color.black); G.DrawString ( "버전 : 1.0 전원 : Zhonglei", 280, 260); g.setfont (New Font ( "Microsoft Yahei", font.bold, 30)); G. 세트 컬러 (색); g.drawString("―--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- = white} / *** 이중 버퍼링 방법 인터페이스의 각 요소 구성 요소* / public void update (offscreen == null) this. Goffscreen. 이벤트*/ private class keymonitor 확장 keyadapter {public void keyreleased (keyevent e) {int keycode = e.getKeyCode (); if (keyCode == keyEvent.vk_enter) {// 모니터가 사용자가 키보드 Enter 키에 닿는 것을 들으면 다음 작업 SetVisible (false)을 실행합니다. // 환영 인터페이스 숨기기 dataview.setVisible (true); // 모니터링 인터페이스 표시 dataview.dataframe (); // 모니터링 인터페이스 초기화}}}/ * * 스레드를 다시 Repaint (250 밀리 초마다 다시 Repaint) */private class refaintthread implements runnable {public void run () {while (true) {retaint (); try {thread.sleep (250); } catch (InterpruptedException e) {// 리페이트 스레드가 예외를 던지고 예외 세부 사항을 표시 할 때 대화 상자를 만듭니다. String err = exceptionwriter.geterRorinFofRomexception (e); joptionpane.showmessagedialog (null, err, "error", joptionpane.information_message); System.exit (0); }}}}}스크린 샷 실행 :
참고 : 하단 "Enter 키를 클릭하여 기본 인터페이스를 입력하십시오"라는 실제 작동 프로세스에서 플래시 효과가 있습니다 (인터페이스를 한 번에 한 번씩 다시 드로 워킹 하여이 문장이 흰색과 검은 색으로 반복적으로 나타날 수 있습니다). 이중 버퍼링 방법은 다시 드로 워싱 할 때 인터페이스를 깜박 거리는 문제를 해결하는 데 도움이됩니다 (이중 버퍼링 방법을 사용하지 않으면 다시 드로 워킹 할 때마다 이전 인터페이스 비트에 새로운 것을 비트로 그리는 것과 동일하며, 먼저 메모리에서 새 인터페이스를 직접 그리는 것입니다.
dataview.java 코드는 다음과 같습니다. (이 클래스는 직렬 포트 데이터를 실시간으로 표시하는 데 사용됩니다)
간단한 설명 :
하드웨어 장치는 한 번에 매번 직렬 포트를 통해 컴퓨터로 데이터를 보냅니다. 직렬 포트 도구가 하드웨어 장치에 성공적으로 연결되어 모니터링을 추가 한 후에는 데이터를 구문 분석하고 데이터를 수신 할 때마다 인터페이스를 업데이트합니다.
귀하의 요구 사항은 사용할 때 내 요구 사항이 다를 수 있습니다. 이 수업은 참조 용입니다. 실제로 사용하면 데이터 표시 인터페이스 및 데이터 분석 방법을 재현해야 할 수도 있습니다.
패키지 Serialport; import java.awt.button; import java.awt.choice; import java.awt.color; import java.awt.font; import java.awt.frame; import java.awt.graphics; import java.awt.image; import java.awt.label; java.awt. java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.windowadapter; import java.awt.event.windowevent; import java.util.list; import java.util.tomanylistenerseception; import javax.swing.joptionpane; gnu.io.serialport; import gnu.io.serialportevent; import gnu.io.serialporteventlistener; import serixexception. 클라이언트 클라이언트 = null; 개인 목록 <string> commlist = null; // 사용 가능한 포트 번호 저장 개인 Serialport Serialport = NULL; // 직렬 포트 객체 저장 개인 글꼴 font = 새 글꼴 ( "Microsoft Yahei", font.bold, 25); 개인 레이블 tem = 새 레이블 ( "아직 데이터 없음", label.center); // 온도 개인 레이블 HUM = 새 레이블 ( "아직 데이터 없음", label.Center); // 습도 개인 레이블 PA = 새 레이블 ( "아직 데이터 없음", label.Center); // 압력 개인 레이블 비 = 새 레이블 ( "아직 데이터 없음", label.Center); // Rainfall 개인 레이블 Win_Sp = 새 레이블 ( "아직 데이터 없음", label.Center); // 풍속 개인 레이블 WIN_DIR = 새 레이블 ( "아직 데이터 없음", label.Center); // 바람 방향 개인 선택 commchoice = 새로운 선택 (); // 직렬 포트 선택 (드롭 다운 박스) 개인 선택 BPSCHOICE = New Choice (); // 잘못된 속도 선택 개인 버튼 OpenSerialButton = 새 버튼 ( "직렬 포트 열기"); 이미지 오프 스크린 = null; // 페인팅시 캔버스 // Window Toolkit 툴킷의 아이콘을 설정합니다. 툴킷 = getToolKit (); Image Icon = Toolkit.getImage (dataview.class.getResource ( "computer.png")); / *** 클래스 생성자* @param client*/ public dataview (클라이언트 클라이언트) {this.client = client; commlist = serialtool.findport (); // 프로그램이 초기화 될 때 유효한 직렬 포트를 한 번 스캔} /*** 기본 메뉴 창이 표시됩니다. * 라벨, 버튼, 드롭 다운 바 및 관련 이벤트 청취를 추가합니다. */ public void dataframe () {this.setbounds (client.loc_x, client.loc_y, client.width, client.height); this.settitle ( "cdio project"); this.seticonimage (아이콘); this.setbackground (color.white); this.setLayout (null); this.addwindowlistener (새 WindowAdapter () {public void windowclosing (windowevent arg0) {if (serialport! = null) {// 프로그램이 종료 될 때 SerialTool.closeport (serialport);} system.exit (0);}); Tem.setBounds (140, 103, 225, 50); tem.setbackground (color.black); tem.setfont (font); tem.setforeground (color.white); 추가 (TEM); Hum.setBounds (520, 103, 225, 50); hum.setbackground (color.black); hum.setfont (font); hum.setforeground (color.white); 추가 (hum); Pa.setBounds (140, 193, 225, 50); Pa.setbackground (color.black); PA.SETFONT (FONT); pa.setforeground (color.white); 추가 (PA); Rain.SetBounds (520, 193, 225, 50); Rain.setbackground (color.black); Rain.SetFont (글꼴); Rain.setforeground (Color.white); 추가 (비); win_sp.setbounds (140, 283, 225, 50); win_sp.setbackground (color.black); win_sp.setfont (font); win_sp.setforeground (color.white); 추가 (win_sp); win_dir.setBounds (520, 283, 225, 50); win_dir.setbackground (color.black); win_dir.setfont (font); win_dir.setforeground (color.white); 추가 (win_dir); // 직렬 포트 선택 옵션 추가 commchoice.setbounds (160, 397, 200, 200); // 사용 가능한 직렬 포트가 있는지 확인하십시오. if (commlist == null || commlist.size () <1) {joptionpane.showmessagedialog (null, "유효한 직렬 포트가 발견되지 않았습니다!", "오류", joptionpane.information_message); } else {for (문자열 s : commlist) {commchoice.add (s); }} add (commchoice); // 보드 속도 옵션 추가 bpschoice.setbounds (526, 396, 200, 200); bpschoice.add ( "1200"); bpschoice.add ( "2400"); bpschoice.add ( "4800"); bpschoice.add ( "9600"); bpschoice.add ( "14400"); bpschoice.add ( "19200"); bpschoice.add ( "115200"); 추가 (bpschoice); // 직렬 포트 열린 포트 버튼 추가 OpenSerialButton.setBounds (250, 490, 300, 50); OpenSerialButton.Setbackground (Color.LightGray); OpenSerialButton.setfont (New Font ( "Microsoft Yahei", Font.bold, 20)); OpenSerialButton.Setforeground (Color.DarkGray); 추가 (OpenSerialButton); // 열린 직렬 포트 버튼 OpenSerialButton.addactionListener (new ActionListener () {public void actionPerformed (ActionEvent e) {// 직렬 포트 이름 문자열 commname = commchoice.getSelectedEctedEctem (// serial string = bpsChoice를 얻는지 여부를 선택하십시오. (commname == null || commname.equals ( "")) {joptionpane.showmessagedialog (null, "유효한 직렬 포트가 발견되지 않았습니다!", "오류", joptionpane.information_message} else {bpsstr == null | | | | | joptionpane.showmessagedialog. SerialTool.openport (commname, bps); // Joptionpane.showMessagedIalog (null, "모니터가 성공적이며 모니터링 데이터가 나중에 표시됩니다!", "Prompt", JoptionPane.information_Message); } catch (SerialportParameterFailure | NotAserialport | nosuchport | portinuse | toomanylisteners e1) {// 오류가 발생하면 대화 상자를 사용하여 특정 오류 메시지 Joptionpane.showMessagedialog (null, e1, e1, joptionpane.information_message); }}}}}}}); this.setResizable (false); 새 스레드 (new RepaintThread ()). start (); // 리페인트 스레드 시작}/*** 기본 인터페이스 구성 요소 요소를 그립니다. g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "온도 :", 45, 130); g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "습도 :", 425, 130); g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "압력 :", 45, 220); g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "비 :", 425, 220); g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "풍속 :", 45, 310); g.setcolor (color.black); g.setfont (New Font ( "Microsoft Yahei", font.bold, 25)); G.DrawString ( "바람 방향 :", 425, 310); g.setcolor (color.gray); g.setfont (New Font ( "Microsoft Yahei", font.bold, 20)); G.DrawString ( "직렬 포트 선택 :", 45, 410); g.setcolor (color.gray); g.setfont (New Font ( "Microsoft Yahei", font.bold, 20)); G.DrawString ( "나쁜 속도 :", 425, 410); } / *** 이중 버퍼링 메소드 인터페이스의 각 요소 구성 요소* / public void update (그래픽 g) {if (offscreen == null) offscreen = this.createImage (client.width, client.height); 그래픽 GoffScreen = OffScreen.getGraphics (); Color C = Goffscreen.getColor (); Goffscreen.setColor (Color.white); Goffscreen.fillRect (0, 0, client.width, client.height); // 배경 canvas this.paint (goffscreen); // 인터페이스 요소 GOFFSCREEN.SETCOLOR (C); G.DrawImage (오프 스크린, 0, 0, NULL); // 원래 캔버스에 새로 그린 캔버스를 "스프레이"}/ * * Repaint Thread (30 밀리 초마다 다시 Repaint) */private class Repaintthread empless runnable {public void run () {while (true) {// Refaint Method Repaint (); // 사용 가능한 직렬 포트 commlist = serialTool.findport ()를 스캔합니다. if (commlist! = null && commlist.size ()> 0) {// (문자열 s : commlist) {// 일련의 포트 이름이 이미 존재합니까? 초기 기본값은 존재하지 않습니다 (Commlist에 존재하지만 Commchoice에 존재하지 않으면 새로 추가됩니다) 부울 Commexist = false; for (int i = 0; i <commchoice.getItemCount (); i ++) {if (s.equals (commchoice.getItem (i))) {// 현재 스캔 된 직렬 포트 이름은 이미 초기 스캔 Commexist = true에 존재합니다. 부서지다; }} if (commexist) {// 현재 스캔 된 직렬 포트 이름은 이미 초기 스캔에 존재하며 다음 루프는 계속되며; } else {// 존재하지 않는 경우 사용 가능한 직렬 포트 드롭 다운 목록 Commchoice.add (s)에 새 직렬 포트 이름을 추가하십시오. }} // 이미 사용할 수없는 직렬 포트 (int i = 0; i <commchoice.getItemCount (); i ++) {// 초기 기본값은 유효하지 않지만 (commchoice에 존재하지만 공동체에 존재하지 않음) 부울 Commnotexist = true; for (string s : commlist) {if (s.equals (commchoice.getitem (i))) {commnotexist = false; 부서지다; }} if (commnotexist) {//system.out.println("remove " + commchoice.getitem (i)); commchoice.remove (i); } else {계속; }}} else {// 스캔 된 통신 목록이 비어 있으면 기존의 모든 직렬 포트 commchoice.removeall (); } try {thread.sleep (30); } catch (InterruptedException e) {String err = exceptionwriter.geterRorinFofRomexception (e); joptionpane.showmessagedialog (null, err, "error", joptionpane.information_message); System.exit (0); }}}}}} / *** 내부 클래스 형태의 직렬 청취 클래스를 만듭니다* @Author Zhong* / private class serialListener 구현 SerialportEventListener { / *** 핸들 모니터링 된 시리얼 포트 이벤트* / public void serialportevent (serialportevent serialportevent) {swwitchent. serialportevent.bi : // 10 Communication 인터럽트 Joptionpane.showMessagedIalog (null, "Serial Device와의 통신 인터럽트", "오류", JoptionPane.information_message); 부서지다; case serialportevent.oe : // 7 오버 플로우 (오버 플로우) 오류 case serialportevent.fe : // 9 프레임 오류 case serialportevent.pe : // 8 parity 오류 case serialportevent.cd : // 6 캐리어 감지 사례 serialportevent.cts : // 3 SerialPortEvent.dsr : // 4 readyportEvent.ri : // 4 readyportEvent.dr : // 3 명확한 데이터를 보낼 수 있습니다. 벨소리는 case serialportevent.output_buffer_empty : // 2 출력 버퍼가 깨 졌음을 나타냅니다. case serialportevent.data_available : // 1 사용 가능한 데이터는 직렬 포트 // System.out.println ( "발견 된 데이터")에 존재합니다. 바이트 [] data = null; try {if (serialport == null) {joptionpane.showmessagedialog (null, "Serial Port 객체가 비어 있습니다! 모니터링 실패!", "오류", joptionpane.information_message); } else {data = serialTool.readfromport (Serialport); // 데이터를 읽고 바이트 배열에 저장 // system.out.println (새 문자열 (data)); // 구문 분석 프로세스를 사용자 정의하면 실제 사용 프로세스 중에 자신의 요구에 따라 데이터를 수신 한 후 데이터를 구문 분석 할 수 있습니다. (data == null || data.length <1) {// 데이터가 올바르게 읽혀 있는지 확인하십시오. System.exit (0); } else {문자열 dataoriginal = 새 문자열 (data); // 바이트 배열 데이터를 원래 데이터 문자열을 저장하는 문자열로 변환합니다. Datavalid = ""; // 유효한 데이터 (원래 데이터 문자열을 저장하고 시작 * 번호 후 문자열을 제거하는 데 사용) 문자열 [] elements = null; // 원래 문자열을 공백별로 분할 후 얻은 문자열 배열을 저장하는 데 사용됩니다. // 데이터를 구문 분석 if (dataOriginal.charat (0) == ' *') {// 데이터의 첫 번째 문자가 * 숫자 인 경우 데이터 수신이 완료되고 DataValid = dataoriginal.subString (1); 요소 = datavalid.split ( ""); if (elements == null || elements.lenges.length <1) {// 데이터가 정확하게 구문 분석 여부를 확인하십시오. joptionpane.showmessagedialog ( "null,"데이터 구문 분석 프로세스에는 오류가 있습니다. ","오류 ", joptionpane.information_message); System.exit (0); } else {try {// (int i = 0; i <elements.lenges; i ++) {system.out.println (elements [i]); }*///system.out.println("win_dir : " + elements [5]); tem.settext (요소 [0] + "℃"); hum.settext (요소 [1] + " %"); pa.settext (요소 [2] + "HPA"); Rain.settext (요소 [3] + "mm"); win_sp.settext (요소 [4] + "m/s"); win_dir.settext (요소 [5] + "°"); } catch (arrayindExoutOfBoundSexception e) {joptionpane.showMessagedIalog (null, "데이터 분석 프로세스에 오류가 있고 업데이트 인터페이스 데이터가 실패했습니다! 장치 또는 프로그램을 확인하십시오!", "오류", joptionpane.information_message); System.exit (0); }}}}}}} catch (readDataFromseRialPortFailure | serialPortInputStreamCloseFailure e) {joptionpane.showmessagedialog (null, e, "error", joptionpane.information_message); System.exit (0); // 읽기 오류가 발생하면 오류 메시지가 표시된 후 시스템을 종료합니다} break; }}}}스크린 샷 실행 :
전체 프로젝트 소스 코드를 다운로드하십시오 : http://xiazai.vevb.com/201612/yuanma/javaserialmonitor(Vevb.com).rar
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.