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

📄 commframe.java

📁 本源码给出了在jbuilder下实现串口通信,并且如何使用
💻 JAVA
字号:
package comm;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import javax.comm.*;
import java.io.*;
import java.util.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class CommFrame extends JFrame implements Runnable, SerialPortEventListener {
  JPanel contentPane;
  BorderLayout borderLayout1 = new BorderLayout();
  IOBean ioBean = new IOBean();
  ControlBean controlBean = new ControlBean();

  //Communination define
  static CommPortIdentifier portName;
  int portId;
  static Enumeration portList;
  InputStream inputStream;
  OutputStream outputStream;
  SerialPort serialPort;
  Thread readThread;
  static String TimeStamp;


  //Construct the frame
  public CommFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
      commInit();
    }catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void commInit() {
    //Communination ports owned or not
    portId = 1;
    try{
      portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        portName = (CommPortIdentifier) portList.nextElement();
        if (portName.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          if (portName.isCurrentlyOwned()) {
            ioBean.Receiver.append("\nCOM" + portId + " Owned by " + portName.getCurrentOwner());
            TimeStamp = new java.util.Date().toString();
            portId ++;
          }else if (portName.getName().equals("COM" + portId)) {
            break;
          }
        }
      }
      //Communination ports init
      try {
        serialPort = (SerialPort) portName.open("Gooseli_MCU_Control_App", 2000);
        controlBean.CommPortID.setText("COM" + portId);
        controlBean.OnOff.setText("ON");
        controlBean.OnOff.setSelected(true);
        TimeStamp = new java.util.Date().toString();
        System.out.println(TimeStamp + ": msg2 - SerialPort COM" + portId + " is opend");
        ioBean.Receiver.append("\nCOM" + portId + " is opend");
      } catch (PortInUseException e) {
        System.out.println(e);
        ioBean.Receiver.append("\nCOM" + portId + " " + e);
      }
      try {
        inputStream = serialPort.getInputStream();
      } catch (IOException e) {}
      try {
        outputStream = serialPort.getOutputStream();
        outputStream.write((byte)0x01);
        ioBean.Receiver.setText("\nCOM" + portId + ">>" + "Start");
        controlBean.begin.setSelected(true);
      } catch (IOException e) {}
      int BaudRate = 9600;
      System.out.println(controlBean.jComboBox1.getSelectedIndex());
      switch (controlBean.jComboBox1.getSelectedIndex()) {
        case 0:
          BaudRate = 9600;
          break;
        case 1:
          BaudRate = 19200;
      }
      System.out.println(BaudRate);
      try {
        serialPort.setSerialPortParams(BaudRate,
                                       SerialPort.DATABITS_8,
                                       SerialPort.STOPBITS_1,
                                       SerialPort.PARITY_NONE);
      } catch (UnsupportedCommOperationException e) {}
      CommRead();
    }catch(Exception e) {}
  }

  public void commClose() {
    try {
      inputStream.close();
      outputStream.close();
      serialPort.close();
      System.out.println(TimeStamp + ": msg2 - SerialPort COM" + portId + " is closing");
      ioBean.Receiver.append("\nCOM" + portId + " is closing");
    }catch (Exception e) {
       System.out.println(e);
    }
  }

  //Component initialization
  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Serial Ports Communication Current");

    contentPane.add(ioBean,BorderLayout.CENTER);
    contentPane.add(controlBean, BorderLayout.WEST);
    controlBean.OnOff.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          JToggleButton toggle = (JToggleButton) ae.getSource();
          if (toggle.isSelected()) {
            controlBean.OnOff.setText("ON");
            commInit();
          } else {
            controlBean.OnOff.setText("OFF");
            commClose();
          }
        }
      }
    );
    controlBean.begin.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          JToggleButton toggle = (JToggleButton) ae.getSource();
          if (toggle.isSelected()) {
            controlBean.begin.setText("Start");
            try {
              outputStream.write((byte)0x01);
              ioBean.Receiver.setText("\nCOM" + portId + " " + "Start");
            } catch (IOException e) {}
          } else {
            controlBean.begin.setText("Stop");
            try {
              outputStream.write((byte)0x00);
              ioBean.Receiver.append("\nCOM" + portId + " " + "Stop");
            } catch (IOException e) {}
          }
        }
      }
    );

    ioBean.jButton2.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          commWrite();
        }
      }
    );
  }

  public void commWrite() {
    String outString = ioBean.jTextField1.getText();
    if (outString.equals("clear")) {
      ioBean.Receiver.setText("\nCOM" + portId +" Receive:");
    }
    ioBean.jTextField1.setText("Gooseli:");
    try {
      //outputStream.write((byte)0x01);
      outputStream.write(outString.getBytes());
      outputStream.write((byte)0x0D);
      //outputStream.write((byte)0x00);
      ioBean.Receiver.setText("\nCOM" + portId + ">>" + outString);
    } catch (IOException e) {}
  }


  //Communination initialization
  public void CommRead() {
    try {
      serialPort.addEventListener(this);
    } catch (TooManyListenersException e) {}
    serialPort.notifyOnDataAvailable(true);
    readThread = new Thread(this);
    readThread.start();
  }

  public void run() {
    try {
      Thread.sleep(20000);
    }
    catch (InterruptedException e) {}
  }

  public void serialEvent(SerialPortEvent event) {
    switch(event.getEventType()) {
      case SerialPortEvent.BI:
      case SerialPortEvent.OE:
      case SerialPortEvent.FE:
      case SerialPortEvent.PE:
      case SerialPortEvent.CD:
      case SerialPortEvent.CTS:
      case SerialPortEvent.DSR:
      case SerialPortEvent.RI:
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
        break;
      case SerialPortEvent.DATA_AVAILABLE:
        StringBuffer readBuffer = new StringBuffer();
        String scannedInput = null;
        int c;
        try {
          while ((c = inputStream.read()) != 0x00 && c != 0x0D && c != 0x0A) {
            readBuffer.append( (char) c);
          }
          scannedInput = readBuffer.toString();
          ioBean.Receiver.append("\n" + scannedInput);
          TimeStamp = new java.util.Date().toString();
          System.out.println(TimeStamp + ": scanned input received:" + scannedInput);

          inputStream.close();
        } catch (IOException e) {}
        break;
    }
  }

  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      commClose();
      System.exit(0);
    }
  }
}

⌨️ 快捷键说明

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