我是 Java 新手。我正在开发用于 PC 和微 Controller 之间串行通信的 GUI。我正在使用 RXTX 库并且它可以工作。
由于我希望能够从其他类修改 GUI,因此我构建了程序,如下所示:
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
方法,它可以正常工作,但是如果我从使用sl.sendSerial(msg)
的RxTx类,它在j.logger.append("Serial Tx Rx Active.");
行给了我一个空指针异常。我尝试传递字符串变量和从 RxTx
到 Serial
的书面文本根本不起作用。它总是在 j.logger.append 行中给我一个空指针异常!!!如果我注释掉该行,它仍然不起作用。在那种情况下绝对不会发生任何事情。没有错误,什么也没有。在这种情况下,串行 TX 也不起作用。仅当我从主类调用方法时,附加和串行通信才有效。但我需要从 RxTx 类调用它。
那么为什么,如果我从主类调用方法,一切都会正常,但如果从 RxTx 类调用串行类中的方法,一切都会崩溃。你们能帮我解决这个问题吗?
谢谢
最佳答案
您的变量private Serial sl
只是未初始化。
尝试一下
public RxTx(GUI g){
this.g = g;
this.sl = new Serial(g);
}
关于java - 如果从一个类调用该方法,但从另一个类调用则该方法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428583/