sorry about the title I had trouble finding out what I should call it.
So here is the deal! I am currently creating a chat application where I use a Gui using I've created in JavaFx (a Gui that has some graphics on it but I think that is kinda irrelevant) what I have done so far is that I've setup a small server that each client connect to through the program! The main idea is that the clients sends a message to the server and the server will then send it to the other client (which is the whole idea in a chat program) one important note is that I am not using Threads and do not wish to yet!
So to get down to the real problem:
I've created a client class that contains methods to connect, receive and send. my Connect class works fine with my Gui and I am able to connect to the server without any problems!
The problem begins when I try to send to or receive from my server. No matter how many exceptions I throw or how many try Catch I do I get a nullpointer error! I've looked at the code for about 2 hours trying to figure out the problem but without luck! my code are as following:
Client class:
private PrintWriter pw;
/**
* #param args
* #throws IOException
*/
public void connect() throws IOException{
final int portNumber = 6040;
// du kan vælge at bruge inetadressen til at connecte i socketet.
InetAddress adr = InetAddress.getByName("localhost");
Socket socket = new Socket("localhost", portNumber);
pw = new PrintWriter(socket.getOutputStream());
// outPut - Programmet sender til serveren
pw.println("Connected waiting for input");
pw.flush();
//input - Serveren sender til programmet;
}
public void Send(String x) throws IOException{
if (x != null) {
pw.print(x);
pw.flush();
}else {
System.out.println("ingen meddelse");
}
}
public String getInformation(){
Scanner informationFromServer = new Scanner(System.in);
String x = informationFromServer.nextLine();
if (x== null) {
return "";
}
return x;
}
my simpleController code (the code that controls my GUI):
public class SimpleController implements Initializable{
public Button btn_Connect;
private Client client;
public Label chatPerson3;
public Label chatPerson1;
public Label lbl_Chatperson1_userName;
public TextField txt_userName;
public TextField textField_chat;
public TextField txt_ChatPerson1;
public Button Send;
public TextField txt_ChatPerson2;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
btn_Connect.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
chatPerson1.setVisible(true);
lbl_Chatperson1_userName.setText(txt_userName.getText());
}
});
Send.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String x = textField_chat.getText();
textField_chat.setText("");
txt_ChatPerson1.setVisible(true);
txt_ChatPerson1.setText(x);
System.out.println(x);
try {
client.Send(x);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}}
and last but not least my main:
public class Main extends Application{
public static void main(String[] args) throws IOException{
Application.launch(Main.class, (java.lang.String[]) null);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
Client c = new Client();
c.connect();
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("testingBackground.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Chatten");
primaryStage.show();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
}
}
The exception I get when I try to send is of course in my client.send() method and if I try to receive before I send then it is in the client.getInformation() method.
What have I done wrong? What am I missing?
Related
I have a big problem with an exercise from my java teacher.
In theory the exercise must have the following points:
-Sockets
-Clients
-Server
-The server uses MySql for something
-Login
-Md5 to save the passwords
-Secure socket
With this I decide to make a chat in theory should be easy stuff but... I'm completely lose.
More or less I made the basic (Secure Socket, server, clients) but even that doesn't work, but the IDE makes no fail in theory should be fine.
Someone May help me?
The code is just below:
ChatClient this make work the client, loading the interface and the features:
public class ChatClient
{
private Socket s;
private ClientPanel panel;
public static void main(String[] args)
{
new ChatClient();
}
public ChatClient()
{
try
{
Window();
s = new Socket("localhost" , 5557);
ClientControl control = new ClientControl(s, panel);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void Window()
{
JFrame v = new JFrame();
panel = new PanelCliente(v.getContentPane());
v.pack();
v.setVisible(true);
v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
ServerChat this create a server chat with secure sockets as one of the requisites of the exercise:
public class ServerChat extends Thread
{
public static void main(String[] args)
{
int port= 5090;
SSLServerSocketFactory sslserver = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
try
{
SSLServerSocket sslsocket = (SSLServerSocket)sslserver.createServerSocket();
InetSocketAddress socketAddress = new InetSocketAddress("localhost" , port);
while(true)
{
SSLSocket socket = (SSLSocket)sslsocket.accept();
System.out.println("Client: " + socket.getInetAddress().getHostName() + " Conected");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public class ClientControl implements ActionListener, Runnable
{
private DataInputStream dataInput;
private DataOutputStream dataOutput;
private ClientPanel panel;
public ClientControl (Socket s, ClientPanel panel)
{
this.panel = panel;
try
{
dataInput = new DataInputStream(s.getInputStream());
dataOutput = new DataOutputStream(s.getOutputStream());
panel.addActionListener(this);
Thread t = new Thread(this);
t.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void actionPerformed (ActionEvent event)
{
try
{
dataOutput.writeUTF(panel.getTexto());
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
String text = dataInput.readUTF();
panel.addTexto(text);
panel.addTexto("\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client Thread in theory this make posible to run the client as a thread and implements it's functions:
public class ClientThread implements Runnable, ListDataListener
{
private DefaultListModel conversation;
private Socket s;
private DataInputStream dataInput;
private DataOutputStream dataOutput;
public ClientThread (DefaultListModel conversation, Socket s)
{
this.conversation = conversation;
this.s = s;
try
{
dataInput = new DataInputStream(s.getInputStream());
dataOutput = new DataOutputStream(s.getOutputStream());
conversation.addListDataListener(this);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while (true)
{
String text = dataInput.readUTF();
System.out.println(text);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void intervalAdded(ListDataEvent e)
{
String text = (String) conversation.getElementAt(e.getIndex0());
try
{
dataOutput.writeUTF(text);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
#Override
public void contentsChanged(ListDataEvent arg0)
{
}
#Override
public void intervalRemoved(ListDataEvent arg0)
{
}
}
Client Panel is below basically makes a simple design with JSwing to create and interface where you see the conversation and you can writte whatever you want:
public class ClientPanel
{
private JScrollPane scroll;
private JTextArea textArea;
private JTextField textField;
private JButton button;
public ClientPanel(Container cont)
{
cont.setLayout(new BorderLayout());
textArea = new JTextArea();
scroll = new JScrollPane(textArea);
JPanel panel = new JPanel(new FlowLayout());
textField = new JTextField(50);
button = new JButton("Send");
panel.add(textField);
panel.add(button);
cont.add(scroll, BorderLayout.CENTER);
cont.add(panel, BorderLayout.SOUTH);
}
public void addActionListener (ActionListener action)
{
textField.addActionListener(action);
button.addActionListener(action);
}
public void addTexto (String text)
{
textArea.append(text);
}
public String getTexto()
{
String text = textField.getText();
textField.setText(text);
return text;
}
}
How can I add a database to Log in users?
How can I add there Md5 to protect the passwords?
How can I make this all work together?
That's my questions
You have a server and clients and want to write a chat. So the server is the center and holds the connection to the database where all persistent data is stored. The password is not stored as plain text, only it's md5 hash is stored in database.
Furthermore, only the server holds a connection to the database.
This answers where to use MD5 and which guy the master of the database is.
You have already created a SeverChat. That guy is responsible to listen for new clients to connect. If a new client wants to connect, the ServerChat has to spawn a new ClientController.
Your ClientControl does not look like what I mean. A ClientControll is responsible to take the request from the specific client he is connect to, handle the request and send an answer to the client.
That means you need some sort of a protokol. You can use ObjectStreams to send objects from the client to the sever and vice versa.
This makes it easier to define a protokol.
To get an idea of the ClientController:
class ClientController extends Thread {
private final ObjectInputStream dataInput;
private final ObjectOutputStream dataOutput;
private boolean loggedIn = false;
ClientController(ObjectInputStream dataInput, ObjectOutputStream dataOutput) {
this.dataInput = dataInput;
this.dataOutput = dataOutput;
}
#Override
public void run() {
try {
boolean stayConnected = true;
while (stayConnected) {
Object data = dataInput.readObject();
if (data instanceof LoginAction) {
// check data an do login
this.loggedIn = true;
dataOutput.write(new LoginResponse(/* response data */));
}
if (data instanceof RequestChatDataAction) {
if (this.loggedIn) {
dataOutput.write(new NotLoggedInResponse());
} else {
dataOutput.write(new ChatDataResponse(/* chat data.. */));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The LoginAction, LoginResponse a.s.o. objects define your protokol. You need of cause more objects to implement all features and these objects have to implement java.io.Serializable. Otherwise, you will not be able to send them over the wire.
You have to write counter part as well - the client.
The client starts up, connects to the server and tries to login. If login is successfull, the client waits for new chat data and displays it.
If the user types in something, this data is send to the server and will be added to the 'gobal' chat data.
I would recommend not to add the gui elements before the client-server communication is done. You can use the System.out and System.in to interact with the user.
So, I hope that helps you.
Furthermore, SO is not for questions like: Do my homework. I see that you already have taken the tour.
Reading How to create a Minimal, Complete, and Verifiable example would be appreciated.
I need to wait for a Server program to send data to the Client program using a socket so I must wait for it using a while loop. However the Client program is a JavaFX Application and if used in a while loop it will freeze up and crash so I put the while loop in a new Thread. However the body of this while loop needs to update the JavaFX UI which cannot be done as it causes "Not on FX application thread;" Exception so I cannot create a new thread for it.
This is my code:
import static util.Constants.PORT;
import static util.Constants.SERVER_NAME;
public class Client extends Application {
private static View view;
public static Scanner in;
public static PrintWriter out;
private static boolean appRunning = true;
public static void main(String[] args) {
try {
Socket socket = new Socket(SERVER_NAME, PORT);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
launch(args);
} catch (IOException e) {
System.out.println("Could not establish connection to server. Program terminating..");
System.exit(1);
}
}
#Override
public void start(Stage window) throws Exception {
// This is a JavaFX BorderPane that adds itself to window:
view = new View(window);
// ServerListener
new Thread(() -> {
try {
while (appRunning) {
// will through exception. needs to run on Application thread:
parseServerMessage(Client.in.nextLine());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}).start();
}
private static String[] parseServerMessage(String message0 {
// update the JavaFX UI
}
}
and if I used this code below in the start method without the thread, the JavaFX app will freeze:
#Override
public void start(Stage window) throws Exception {
// This is a JavaFX BorderPane that adds itself to window:
view = new View(window);
// causes JavaFX to freeze:
while (appRunning) {
parseServerMessage(Client.in.nextLine());
}
}
Also putting the thread to sleep doesn't help.
How can I get around this problem? Thank you!
EDIT Solution:
Thanks to the solution, I edited my code and now it works perfectly. Here is the edited solution:
new Thread(() -> {
while (true) {
String serverMessage = Client.in.nextLine();
Platform.runLater(() -> {
parseServerMessage(serverMessage);
});
}
}).start();
You can take a look at Platform::runLater. From the JavaDoc:
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller.
I am currently creating a service allowing to send objects from a client to a server and vice-versa, but experiencing an issue that I unfortunately cannot explain and fix.
First of all, here are the useful classes (I haven't put all methods such as getters and setters in this post).
/**
* This launcher creates a NetworkInterface, waits for a connection, sends a message to the connected client and waits for an incoming message
*
*/
public class ServerLauncher {
public static void main(String[] args) {
try {
NetworkSystem n = new NetworkSystem(4096);
n.startServerManager();
while (n.getCommunications().isEmpty()) {
// this line is unexpectedly magic
System.out.println("Waiting for a new connection...");
}
do {
n.getCommunications().get(0).send(new String("Hello, are you available?"));
} while (n.getCommunications().get(0).getReceiveManager().getReadObjects().isEmpty());
System.out.println(n.getCommunications().get(0).getReceiveManager().getReadObjects().get(0));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* This launcher creates a NetworkSystem, connects to the server, waits for an incoming message and anwers back
*
*/
public class ClientLauncher {
public static void main(String[] args) {
try {
NetworkSystem n = new NetworkSystem(8192);
n.instanciateCommunication(new Socket(InetAddress.getLocalHost(), 4096));
while (n.getCommunications().get(0).getReceiveManager().getReadObjects().isEmpty()) {
// this line is unexpectedly magic
System.out.println("Waiting for an object...");
}
System.out.println(n.getCommunications().get(0).getReceiveManager().getReadObjects().get(0));
n.getCommunications().get(0).getSendManager().send(new String("No, I am not! We will talk later..."));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* This class handles every incoming messages.
*/
public class ReceiveManager implements Runnable {
private ObjectInputStream inputStream;
private CommunicationManager communicationManager;
private List readObjects;
private boolean receive;
public ReceiveManager(CommunicationManager communicationManager) throws IOException {
this.communicationManager = communicationManager;
this.inputStream = new ObjectInputStream(this.communicationManager.getSocket().getInputStream());
this.readObjects = new ArrayList();
this.receive = true;
}
#Override
public void run() {
Object object = null;
try {
while ((object = this.inputStream.readObject()) != null && this.hasToReceive()) {
this.readObjects.add(object);
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.setContinueToReceive(false);
}
}
private boolean hasToReceive() {
return this.receive;
}
public void setContinueToReceive(boolean value) {
this.receive = value;
}
}
/**
* This class allows the user to send messages
*/
public class SendManager {
private ObjectOutputStream outputStream;
private CommunicationManager communicationManager;
public SendManager(CommunicationManager communicationManager) throws IOException {
this.communicationManager = communicationManager;
this.outputStream = new ObjectOutputStream(this.communicationManager.getSocket().getOutputStream());
}
public void send(Object object) throws IOException {
this.outputStream.writeObject(object);
this.outputStream.flush();
}
}
So basically, as you may have noticed in the ServerLauncher and the ClientLauncher, there are two "magic" instructions. When those two lines are commented and I run the server then the client, nothing happens. The server and the client are simply running and never stop. However, when I uncomment these two magic lines, every works like a charm: messages are properly sent and received.
Would you guys know the reason of this unexpected behaviour ?
Oh yeah, I forgot, if you guys want me to upload everything to test the project or whatever, just tell me :-)
You're starving the CPU with those spin loops. You should sleep or wait while the queues are empty, or better still just take()from blocking queues.
NB Your loop condition isn't correct:
readObject() doesn't return null at end of stream. It throws EOFException.
You should also test hasToReceive() before calling readObject() rather than afterwards. Otherwise you always do an extra read.
I'm doing a Platform.RunLater to update a TextField. Here you can see the code:
public class FXMLDocumentController implements Initializable {
#FXML
private TextField carlos;
RXTX main = new RXTX();
public void Test(){
Platform.runLater(new Runnable() {
#Override public void run() {
carlos.setText("Test");
}
});
}
#Override
public void initialize(URL url, ResourceBundle rb) {
main.initialize();
Thread t=new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
And that:
public class RXTX implements SerialPortEventListener{
private String Temperature;
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM4" // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
GetData(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
#FXML
private void GetData(String Data) {
if(Data.contains("Temperature")){
FXMLDocumentController main = new FXMLDocumentController();
main.Test();
}
}
}
Well, so I doesn't work. It return an error like that:
Exception in runnable java.lang.NullPointerException at
openpilot.FXMLDocumentController$1.run(FXMLDocumentController.java:35)
at
com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:182)
at
com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at java.security.AccessController.doPrivileged(Native Method) at
com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:179)
at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at
com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
at java.lang.Thread.run(Thread.java:744)
Don't use new to create an FXML controller, use FXMLLoader.load().
In your particular case, it is probably best to call the load() on the JavaFX application thread using Platform.runLater().
It is the FXMLLoader which creates instances of your #FXML annotated nodes. So unless you use the loader, the #FXML nodes will never be created. So in this case, your "carlos" TextField is null because nothing ever creates such a TextField, leading to your NullPointerException.
The NullPointerException error has nothing to do with runLater working or not working.
There are probably quite a few other errors in your code as well.
I suggest spending more time writing basic single-threaded JavaFX applications first before tackling multi-threaded apps communicating with a serial port.
I am trying to "connect" two classes together, MyJFrame and MySerialPort, using the interface SerialPortListener, but I am clueless as how to do it. The reason I am doing this is because yesterday I had a problem assigning data from a serial port buffer to a global String (finalString), in the MySerialPort class. This string should be returned to MyJFrame where a label displays it. The problem was that my label would display finalString before anything
was assigned to finalString, since classes were running in different threads. I posted the question on the forum and received a suggestion to use interface to connect their threads, and I modified the code according. Where do I use the keyword implements SerialPortListener and how do I get the value?
SerialPortListener Interface code
public interface SerialPortListener {
void stringReveivedFromSerialPort(String s);
}
MyJFrame class code
public class MyJFrame extends JFrame{
public MySerialPorts msp = new MySerialPorts();
public MyJFrame(){
initComponents();//draws GUI components
initSerialPorts();//initializes serial ports
}
private void initSerialPorts(){
msp.getPortName();//gets serial port's name (in this example COM1)
msp.openPort();//opens the communication for port COM1
}
private String firmwareVersion(){
//This is the method I call when I want to get the Firmware Version
msp.getFirmwareVersion();//sends command to receive reply from serial device
lblFirmwareVersion.setText();//label that prints the firmware version String
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainJFrame().setVisible(true);
}
});
}
private JLabel lblFirmwareVersion;
}
MySerialPort class code
public class MySerialPort {
//this method is using the jSSC API (java simple serial connector)
//http://code.google.com/p/java-simple-serial-connector/
private SerialPort serialPort;
private int iBaudRate = SerialPort.BAUDRATE_57600;
private int iDataBits = SerialPort.DATABITS_8;
private int iStopBits = SerialPort.STOPBITS_1;
private int iParity = SerialPort.PARITY_NONE;
private String portName = "";
// private String finalString = "";
// private StringBuilder sbBuffer = new StringBuilder();
private List<SerialPortListener> portListeners = new ArrayList<SerialPortListenerInterface>();
public void addMyPortListener(SerialPortListener listener) {
portListeners.add(listener);
}
public void removeMyPortListener(SerialPortListener listener) {
portListeners.remove(listener);
}
public void getFirmwareVersion() {
sendPortCommand("<VersFV1A2>\r\n");
}
// public String returnFinalString() {
// return finalString;
// }
public void getPortName() {
String[] ports = SerialPortList.getPortNames();
portName = ports[0];
}
public void openPort() {
serialPort = new SerialPort(portName);
try {
if (serialPort.openPort()) {
if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {
serialPort.addEventListener(new Reader(), SerialPort.MASK_RXCHAR
| SerialPort.MASK_RXFLAG
| SerialPort.MASK_CTS
| SerialPort.MASK_DSR
| SerialPort.MASK_RLSD);
} else {
//Error Message - Can't set selected port parameters!
serialPort.closePort();
}
} else {
//Error Message - Can't open port!
}
} catch (SerialPortException | HeadlessException ex) {
//Error Message - Can't open port! - Do nothing
}
}
private void sendPortCommand(String sSendPortCommand) {
if (sSendPortCommand.length() > 0) {
try {
serialPort.writeBytes(sSendPortCommand.getBytes());
} catch (Exception ex) {
//Error Message - Error occured while sending data!
}
}
}
private class Reader implements SerialPortEventListener {
private String sBuffer = "";
#Override
public void serialEvent(SerialPortEvent spe) {
if (spe.isRXCHAR() || spe.isRXFLAG()) {
if (spe.getEventValue() > 0) {
try {
//Read chars from buffer
byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
sBuffer = new String(bBuffer);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
for (SerialPortListenerInterface listener : portListeners) {
listener.stringReveivedFromSerialPort(sBuffer);
}
}
});
// The following is the code I had prior to suggestion of using invokeLater instead of invokeAndWait
//
// sbBuffer.setLength(0);
//
// SwingUtilities.invokeAndWait(
// new Runnable() {
//
// #Override
// public void run() {
// sbBuffer.append(sBuffer);
// }
// });
//
// finalString = new String(sbBuffer);
} catch (Exception ex) {
}
}
}
}
}
}
Here's some code that you could add to your initSerialPorts() method, and which would open a dialog box displaying the text received from the serial port:
msp.addMyPortListener(new SerialPortListener() {
#Override
public void stringReveivedFromSerialPort(String s) {
JOptionPane.showMessageDialog(MyJFrame.this, s);
}
});
It creates an anonymous SerialPortListener instance, which displays a dialog box containing the received text as message, and adds it to your MySerialPort msp instance.
I believe that you want your MyJFrame class to implement SerialPortListener:
public class MyJFrame extends JFrame implements SerialPortListener {
/* blah */
#Override
public void stringReveivedFromSerialPort(String s) {
lblFirmwareVersion.setText(s);
}
/* blah */
}