2013-03-19 63 views
0

我寫了一個名爲ArduinoSerial的類來實現SerialPortEventListener覆蓋serialEvent兩次

我使用這個類作爲一個庫,我導入到另一個名爲ArduinoGUI的程序中,該程序創建一個帶有一系列複選框的swing GUI。

當我想寫入串口我有一個私人成員變量ArduinoGUI類私人ArduinoSerial arduino;

我打電話給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類不首先讀取並放棄緩衝區。

回答

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

} 
+0

的一個問題是:公共類ArduinoGUI已經擴展了javax.swing.JFrame,它是否可以擴展ArduinoSerial? – Zac 2013-03-19 15:26:45

+0

您不能擴展2個類,只有1個可用。 – 2013-03-19 15:32:09

+0

如何解決這個問題,我創建了ArduinoSerial作爲實現SerialPortEventListener的抽象類,但不是serialEvent方法。我的子類已經擴展了jFrame,它需要創建GUI,我怎樣才能讓它擴展ArduinoSerial,以便它可以實現缺少的SerialPortEventListener? – Zac 2013-03-20 10:11:55