I am new to Java. I am working on a GUI for Serial Communication between a PC and a Microcontroller. I am using the RXTX Library and it works.
As i want to be able to modify the GUI from another Classes, i built the Programm as follows:
1: Main Class: ( Constructor not being used )
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: Serial 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);
}
}
The Problem is if i call the sendSerial
Method from GUI Class using s.sendSerial("TEST");
, it works perfectly, but if i call it from RxTx Class using sl.sendSerial(msg)
, it gives me a nullpointerexceprion at line j.logger.append("Serial Tx Rx Active.");
I tried passing String Variabels and written Text from RxTx
to Serial
it just never works. It always gives me a nullpointerexception in the j.logger.append line!!! If i comment that line out, it still doesn't work. In that Case absolutely nothing happens. No errors no nothing. The Serial TX doesn't work also in that case. The appending and serial Communication only works if i call the Method from the Main Class. But i need to call it from RxTx Class.
So why is it, that everything works fine if i call the Method from the Main Class but all hell breaks loose if call the Method in Serial Class from RxTx Class. Can you guys please help me resolving the issue?
Thank You
答案 0 :(得分:1)
Your variable private Serial sl
is just not initialized.
Try
public RxTx(GUI g){
this.g = g;
this.sl = new Serial(g);
}
答案 1 :(得分:0)
You have to consider that both declarations of Serial
variable are differents, I mean, in one of them you use the constructor of the class Serial
and in the other one you just use a private statement so in the first one you make reference to the class Serial
but in the second one not.
Try to change
private Serial sl;
to
Serial sl = new Serial(this);
I expect it will fix your error.