0

我写了一个名为ArduinoSerialimplements的类SerialPortEventListener

我使用这个类作为一个库,我将它导入到另一个名为 的程序ArduinoGUI中,该程序创建了一个带有一系列复选框的摇摆 GUI。

当我想写入串行端口时,我有一个私有arduinoArduinoGUI类的私有成员变量;ArduinoSerial

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

问题是内部ArduinoSerial类覆盖了读取函数,并且当前将输出吐出到 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类不读取并首先丢弃缓冲区。

4

1 回答 1

1

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

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);

}
于 2013-03-19T14:28:27.263 回答