⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 communication.java

📁 一个串口通信程序
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.text.DecimalFormat;
import javax.comm.*;
import javax.swing.*;


public class Communication extends JFrame implements ActionListener, SerialPortEventListener
{
	private JTextArea sendWindow,receiveWindow;
	private JLabel informatiomLabel;
	private JButton send,connect,cut,set;
	private CommPortIdentifier portid = null;
	private SerialPort serialPort;
    private InputStream in = null;	
    private String SerialPortName="COM1";
    private JMenu helpMenu;
    private JMenuItem topHelp,aboutCal;
    private JMenuBar mainMenu;
    private JTextArea help;
    private JScrollPane scrollHelp;
    private JFrame frame;
	
    private JPanel panel,panel1,messagePanel,buttonPanel,informationPanel;
	
	public Communication()
	{	
		panel=new JPanel();
		
		mainMenu = new JMenuBar();
		helpMenu = new JMenu("帮助");
	
		topHelp = new JMenuItem(" 帮助主题");
        topHelp.addActionListener(this);
        help = new JTextArea(5, 20);
        scrollHelp = new JScrollPane(help);
        help.setEditable(false);
        
        aboutCal = new JMenuItem(" 关于串口通信程序");
        aboutCal.addActionListener(this);
        
        helpMenu.add(topHelp);
        helpMenu.add(aboutCal);
        mainMenu.add(helpMenu);
        
        help.append("串口通信使用\n");
        help.append("1. 打开串口进行设置。\n");
        help.append("2. 选择要使用的串口,点击确定。\n");
        help.append("3. 点击“连接串口”,查看状态。\n");
        help.append("4. 在发送框编辑要发送的信息,点击“发送信息”。\n");
        help.append("5. 通信完毕后关闭程序\n");
        
  		panel.add(mainMenu,BorderLayout.NORTH);
		
		messagePanel = new JPanel();	
		messagePanel.setLayout(new FlowLayout());
		messagePanel.setBackground(Color.cyan);
		messagePanel.setPreferredSize(new Dimension(400,350));
		
        sendWindow= new JTextArea(6,30);
		sendWindow.setEditable(true);
		sendWindow.setBorder(BorderFactory.createLineBorder(Color.red,3));
        receiveWindow=new JTextArea(6,30);
		receiveWindow.setEditable(false);
		receiveWindow.setBorder(BorderFactory.createLineBorder(Color.red,3));
		
		messagePanel.add(new JLabel("信息接收框"));
		messagePanel.add(receiveWindow);
		messagePanel.add(new JLabel("信息发送框"));
		messagePanel.add(sendWindow);
		
		send=new JButton("发送信息");
		send.setEnabled(false);
		send.addActionListener(this);
        connect=new JButton("连接串口");
		connect.addActionListener(this);
        cut=new JButton("关闭串口");
        cut.setEnabled(false);
		cut.addActionListener(this);
        set=new JButton("打开串口");
		set.addActionListener(this);
		
		buttonPanel=new JPanel();		
		buttonPanel.add(set);
		buttonPanel.add(connect);
		buttonPanel.add(send);		
		buttonPanel.add(cut);		
		buttonPanel.setLayout(new GridLayout(2,2));
	    buttonPanel.setPreferredSize(new Dimension(400,100));
	    panel.add(buttonPanel,BorderLayout.SOUTH);
		
		informationPanel = new JPanel();
		informatiomLabel=new JLabel("连接状态:");
		informationPanel.add(informatiomLabel);
		informationPanel.setPreferredSize(new Dimension(400,50));
		messagePanel.add(informationPanel,BorderLayout.SOUTH);
		panel.add(messagePanel,BorderLayout.CENTER);
		
		panel.setPreferredSize(new Dimension(400,480));
		
		frame = new JFrame("串口通信");
		frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
		frame.getContentPane().add(panel);
		frame.setLocation(400,100);
		frame.pack();
		frame.setVisible(true);		
		
		addWindowListener(new WindowAdapter()
		{ 
		public void windowClosing(WindowEvent we){ 
		    System.out.println("已关闭通信程序");
			System.exit(0); 
		}});	
	}
	
	public void actionPerformed(ActionEvent e) {
		 if(e.getSource()==send)
		 {	 
			 sendData();			 
		 }	
		 if(e.getSource()==connect)
		 {	 
		     openPort();
			 send.setEnabled(true);
			 cut.setEnabled(true);
			 connect.setEnabled(false);
			 set.setEnabled(false);
		 }
		 if(e.getSource()==cut)
		 {	 
			 portClose();
		     connect.setEnabled(true);
		     set.setEnabled(true);
		     send.setEnabled(false);
		     cut.setEnabled(false);
		 }
		 if(e.getSource()==set)
		 {
			 set();			 
		 }
		 if (e.getSource()==topHelp) 
                  {
                     JOptionPane.showMessageDialog(panel, scrollHelp);
                  }
               if (e.getSource()==aboutCal) 
                 {
                     JOptionPane.showMessageDialog(panel, "Java编写的串口通信程序");
                 }
	 }
	 
	 public void openPort()
	 {		   		   		
		try {			
			portid = CommPortIdentifier.getPortIdentifier(SerialPortName);
			informatiomLabel.setText(portid.getName()+"已开启");
			serialPort = (SerialPort)portid.open("SerialCommunication",2000);
			serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);		   		   		    		    		    			     	    
			serialPort.addEventListener(this);
			serialPort.notifyOnDataAvailable(true);
			
		}catch(Exception e){
			informatiomLabel.setText(portid.getName()+"已占用或不存在");
			  }					
	 }
	 	 
	 public void sendData()
	 {
		 try{
			 OutputStream out; 
			 out = serialPort.getOutputStream();
			 out.write(sendWindow.getText().getBytes());	
			 sendWindow.setText("");
			 informatiomLabel.setText("消息已发送");
			 }catch(Exception e1){
				 System.out.println(e1.toString());
			 }			
	 }
	 		 
	 public void receiveData()
	 {    		 	 
		 String s="";
		 byte[] readBuffer = new byte[512]; 		 
		 int tempNum;
		 try{
	     in=serialPort.getInputStream();		
		 tempNum = in.read(readBuffer);
		 byte[]a= new byte[tempNum]; 
		 System.arraycopy(readBuffer, 0, a, 0, tempNum);
		 s=new String(a);
		 receiveWindow.setText(s);
		 informatiomLabel.setText("收到新消息");		 
		 }catch(Exception e2){
			 System.out.println(e2.toString());
		 }		 
	 }
	 
	 private void set()
	 {
		 String s="";
		 int i=0;
		 Enumeration en = CommPortIdentifier.getPortIdentifiers();
		 CommPortIdentifier portId;
		 while (en.hasMoreElements())
		 {
          portId = (CommPortIdentifier) en.nextElement();
		 /*如果端口类型是串口,则打印出其端口信息*/
         if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
         {
          s=s+portId.getName()+"\n";
         }
         }
		 JPanel setPanel=new JPanel();
		 JPanel Panel1=new JPanel();
		 JLabel JLabel1=new JLabel("正用串口:");
		 JLabel JLabel2=new JLabel("可用串口:");
		 JTextArea ComInformation=new JTextArea();
		 ComInformation.setText(s);
		 ComInformation.setEditable(false);
		 JTextField ComName=new JTextField(5);
		 ComName.setText("COM1");
		 
		 Panel1.add(JLabel1);
		 Panel1.add(ComName);
		 setPanel.add(Panel1);
		 setPanel.add(JLabel2);
		 setPanel.add(ComInformation);
		 setPanel.setLayout(new FlowLayout());
		 
		 String button[]={"确定"};		 		 

		 JOptionPane.showOptionDialog(null,setPanel,"设置串口",JOptionPane.YES_OPTION,
				 JOptionPane.INFORMATION_MESSAGE,null,button,button[0]);
		 SerialPortName=ComName.getText();				 								 						 		 
	 }
	 
	 public void portClose()
	 {
		 try{
			 serialPort.close();	
			 informatiomLabel.setText("运行状态:串口已关闭");
			 }catch(Exception e2)
			 {
				 informatiomLabel.setText("运行状态;串口关闭出错");
			 }			
	 }

	 public void serialEvent(SerialPortEvent event) {
		 switch(event.getEventType()) {
	        case SerialPortEvent.BI:/*Break interrupt,通讯中断*/
	        	informatiomLabel.setText("BI event occured.");
	        case SerialPortEvent.OE:/*Overrun error,溢位错误*/
	        	informatiomLabel.setText("OE event occured.");
	        case SerialPortEvent.FE:/*Framing error,传帧错误*/
	        	informatiomLabel.setText("FE event occured.");
	        case SerialPortEvent.PE:/*Parity error,校验错误*/
	        	informatiomLabel.setText("PE event occured.");
	        case SerialPortEvent.CD:/*Carrier detect,载波检测*/
	        	informatiomLabel.setText("CD event occured.");
	        case SerialPortEvent.CTS:/*Clear to send,清除发送*/
	        	informatiomLabel.setText("CTS event occured.");
	        case SerialPortEvent.DSR:/*Data set ready,数据设备就绪*/
	        	informatiomLabel.setText("DSR event occured.");
	        case SerialPortEvent.RI:/*Ring indicator,响铃指示*/
	        	informatiomLabel.setText("RI event occured.");
	        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,输出缓冲区清空*/
	        	informatiomLabel.setText("OUTPUT_BUFFER_EMPTY event occured.");
	            break;
	        case SerialPortEvent.DATA_AVAILABLE:/*Data available at the serial port,端口有可用
	数据。读到缓冲数组,输出到终端*/
	        	 receiveData();	 
	            
	            break;
	        }		
	}
	 public static void main(String[] args)
		{
		 Communication Comm=new Communication();
		}	
}
	 		

	
	
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -