如果从一个 Class 而不是从另一个调用,则方法有效

Method works if called from one Class but not from another

我是 Java 的新手。我正在开发用于 PC 和微控制器之间串行通信的 GUI。我正在使用 RXTX 库并且它有效。

因为我希望能够从另一个 Classes 修改 GUI,所以我按如下方式构建了程序:

1: Main Class: (未使用构造函数)

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: 序列号 Class:

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 Class:

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 Class 调用 sendSerial 方法,它工作得很好,但是如果我使用 Class 从 RxTx Class 调用它=16=],它在 j.logger.append("Serial Tx Rx Active."); 行给了我一个 nullpointerexceprion 我尝试传递 String Variabels 并将 Text 从 RxTx 写入 Serial 它只是从来没有用过。它总是在 j.logger.append 行中给我一个 nullpointerexception!如果我评论那条线,它仍然不起作用。在那种情况下绝对不会发生任何事情。没有错误没有什么。在这种情况下,Serial TX 也不起作用。仅当我从 Main Class 调用方法时,附加和串行通信才有效。但我需要从 RxTx Class.

调用它

那么为什么,如果我从 Main Class 调用方法,一切正常,但如果从 RxTx Class 调用串行 Class 中的方法,一切都会崩溃.你们能帮我解决这个问题吗?

谢谢

你必须考虑到 Serial 变量的两个声明是不同的,我的意思是,其中一个你使用 class Serial 的构造函数,而另一个你只是使用了一个 private 语句,所以在第一个中你引用了 class Serial 但在第二个中没有。

尝试改变

private Serial sl; 

Serial sl = new Serial(this);

我希望它能解决您的错误。

您的变量 private Serial sl 尚未初始化。 尝试

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