簡體   English   中英

如果從一個類而不是從另一個類調用方法,則該方法有效

[英]Method works if called from one Class but not from another

我是Java新手。 我正在開發用於PC和微控制器之間串行通信的GUI。 我正在使用RXTX庫,它可以工作。

因為我希望能夠從其他類修改GUI,所以我按如下方式構建了Programm:

1:主類:(不使用構造函數)

public class GUI extends JFrame {

Draw panel = new Draw(this);
Code c = new Code(this);
Serial s = new Serial(this);
RxTx r = new RxTx(this);
JTextArea logger;
...
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
GUI frame = new GUI();
frame.create();

         }
    });
public void create(){
...
//builds the GUI
   }
}

2:序列類:

public class Serial implements Runnable{

private GUI j;

public Serial(GUI j){
this.j = j;
}
...
...

public void sendSerial(String message)
{
portName = port;
j.logger.append("Serial Tx Rx Active."); //nullpointerexception here if called from rxtx                            

if (serialPortOpen != true)
return;
try {
      j.logger.append("-");
      outputStream.write(message.getBytes());
} catch (IOException e) {
      j.logger.append("Error while Sending\n");
      }
   }
}

3:RxTx類別:

public class RxTx {

private GUI g;
private Serial sl;
String msg = new String("TEST");

public RxTx(GUI g){
    this.g = g;
}
...
...

public void foo(){

    ...
    ...
    sl.sendSerial(msg);
   }
}

問題是如果我使用s.sendSerial("TEST");從GUI類調用sendSerial方法s.sendSerial("TEST"); ,它可以完美運行,但是如果我使用sl.sendSerial(msg)從RxTx類調用它,它會在第j.logger.append("Serial Tx Rx Active.");行上給我一個nullpointerexceprion j.logger.append("Serial Tx Rx Active."); 我嘗試將String Variabels傳遞並從RxTx寫入Text到Serial但它永遠無法工作。 它總是在j.logger.append行中給我一個nullpointerexception !!! 如果我注釋掉該行,它仍然不起作用。 在那種情況下,絕對不會發生任何事情。 沒有錯誤就沒有。 在這種情況下,串行TX也不起作用。 僅當我從Main Class調用Method時,附加和串行通信才有效。 但是我需要從RxTx類調用它。

所以為什么呢,如果我從Main Class調用方法,那么一切都會很好,但是如果從RxTx Class調用Serial Class的方法,所有的事情都會變得松散。 你們能幫我解決這個問題嗎?

謝謝

您的變量private Serial sl尚未初始化。 嘗試

public RxTx(GUI g){
    this.g = g;
    this.sl = new Serial(g);
}

您必須考慮到Serial變量的兩個聲明都是不同的,我的意思是,在其中一個聲明中,您使用了Serial類的構造函數,而在另一個聲明中,您僅使用了一條私有語句,因此在第一個聲明中,您引用了該類。 Serial但第二個則沒有。

嘗試改變

private Serial sl; 

Serial sl = new Serial(this);

我希望它將解決您的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM