我编写了一个名为ArduinoSerial的类,该类实现了SerialPortEventListener

我将此类用作库,然后将其导入另一个名为ArduinoGUI的程序,该程序将创建一个带有一系列复选框的swing GUI。

当我想写串行端口时,我有一个ArduinoGUI类private ArduinoSerial arduino的private成员变量。

我调用arduino.output.write(byte b);函数,它工作正常。

问题是内部ArduinoSerial类将覆盖read函数,并且当前将输出吐出到system.out。

    @Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine=input.readLine();
            System.out.println(inputLine);

        } catch (Exception e) {
            System.err.println(e.toString());
                            System.out.println("But nothing much to worry about.");
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}


但是,这不是我想要的,我想将串行数据读取到ArduinoGUI类中的字节数组中,但是我不确定如何第二次重写此方法和/或为数据编写事件侦听器在串行端口上,同时使ArduinoSerial类不首先读取和丢弃缓冲区。

最佳答案

是的,您不能两次重写方法,但可以执行以下操作:

public class ArduinoGUI extends JFrame implements ArduinoSerialItf {

private ArduinoSerialItf arduinoSerialItf = null;
private ArduinoSerial arduinoSerial = null;

 //init
 public ArduinoGUI(){
    arduinoSerialItf = this;

   arduinoSerial = new ArduinoSerial(arduinoSerialItf );

 }

@Override
public void onEventReceived(SerialPortEvent oEvent){
   // in GUI class you get event from ArduinoSerial
}

}


创建界面:

public interface ArduinoSerialItf {
 public void onEventReceived(SerialPortEvent oEvent);
}


ArduinoSerial类:

public class ArduinoSerial implements SerialPortEventListener {

private ArduinoSerialItf arduinoSerialItf = null;

public ArduinoSerial(ArduinoSerialItf arduinoSerialItf){
  this.arduinoSerialItf = arduinoSerialItf;
}

@Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
    // when we call this method, event goes to GUI class
    arduinoSerialItf.onEventReceived(oEvent);

}

10-06 06:56