0

I used to work on Swing but now saw that it's pretty obsolete and JX8 is the future for Java applications so I started from YouTube tutorials on FXML GUI from ScreenBuilder. And integrated my RDT 3.0 TCP Server-Client code into FXML GUI.

But I have a lot of errors; I tried solving most of them but every time I get nullPointerException and I know it's because memory is not allocated. How can I get rid of them, and how to get my application running?

Here is the code:

ClientFXMLController.java:

package rdt_app;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import static java.lang.Thread.sleep;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
/**
 * FXML Controller class
 *
 * @author Dell
 */
public class ClientFXMLController implements Initializable {
    ToggleGroup group = new ToggleGroup();
    @FXML
    RadioButton case1;
    @FXML
    RadioButton case2;
    @FXML
    RadioButton case3;
    @FXML
    RadioButton case4;
    @FXML
    RadioButton case5;
    boolean buttonPressed=false;
    String str=null;    
    @FXML
    TextArea msg_rcv;
    @FXML
    Button send_button;
    Socket s;
    DataInputStream in;
//    DataInputStream inn;
    PrintStream ps;
    String pre = "";
    @FXML
    private void handleButtonAction(ActionEvent event) {
//        buttonPressed=true;
        if(s!=null){
            if(case1.isSelected())
                str= "1";
            else if(case2.isSelected())
                str= "2";
            else if(case3.isSelected())
                str= "3";
            else if(case4.isSelected())
                str= "4";
            else if(case5.isSelected())
                str= "5";            
        }
        else{
//                Alert alert = new Alert(Alert.AlertType.ERROR); //AlertType.WARNING
//                alert.setTitle("Error!");
//                alert.setHeaderText("Message Cannot be send at this moment!");
//                alert.setContentText("Please wait for response from Client or timeout and then proceed");
//
//                alert.showAndWait();                
        }
    }    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(ClientFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            // TODO
            case1.setToggleGroup(group);
            case1.setSelected(true);
            case2.setToggleGroup(group);
            case3.setToggleGroup(group);
            case4.setToggleGroup(group);
            case5.setToggleGroup(group);
            msg_rcv.appendText("Key:\n1:Operation with no Loss\n2:Lost Packet\n3:Lost ACK\n4:Premature Timeout\nNull:No Response\n");
            s = new Socket("localHost",8100);
            in = new DataInputStream(s.getInputStream());
//            inn = new DataInputStream(System.in);
            ps = new PrintStream(s.getOutputStream());
            pre = "";
            while (true)
            {
                str = in.readLine();
                if (!str.equalsIgnoreCase("fin") && str!=null)
                {
                    msg_rcv.appendText("Sender just sended a Message: "+str+"\n");
                    if (pre.equalsIgnoreCase("3") || pre.equalsIgnoreCase("null"))
                    {
                        msg_rcv.appendText("Duplicate Detected!\n");
                    }
                    msg_rcv.appendText("Enter a Response: \n");
                    if(str.equalsIgnoreCase("1") || str.equalsIgnoreCase("2") || str.equalsIgnoreCase("3") || str.equalsIgnoreCase("4") ||
                            str.equalsIgnoreCase("5")){
                        pre=str;
                        ps.println(str);
//                        buttonPressed=false;
                    }
//                    str = inn.readLine();
                }
                else if(str==null){
                    // do nothing carry on with loop
                }
                else
                {
                    s.close();
                    break;
                }
            }            
        } catch (IOException ex) {
            Logger.getLogger(ClientFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }


    }    

}

FXMLDocumentController (Server):

package rdt_app;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import static java.lang.Thread.sleep;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
 *
 * @author Dell
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label info_label;
    @FXML
    private Label waitingLabel;
    @FXML
    private Button send_button;
    @FXML
    private TextField msg_send;
    @FXML
    private TextArea msg_rcv;
    @FXML
    private ProgressBar pbar;
    String str =null;
    ServerSocket ss;
    int correct = 0;
    Socket s;
    DataInputStream in;
    DataInputStream inn;
    PrintStream ps;
    @FXML
    private AnchorPane rootPane;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        if(ss!=null && msg_send.getText()!=null){
            if(correct==0)
                str= msg_send.getText();
            else{
                Alert alert = new Alert(AlertType.ERROR); //AlertType.WARNING
                alert.setTitle("Error!");
                alert.setHeaderText("Message Cannot be send at this moment!");
                alert.setContentText("Please wait for response from Client or timeout and then proceed");

                alert.showAndWait();                
            }

        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            // TODO


//            AnchorPane pane = FXMLLoader.load(getClass().getResource("clientFXML.fxml"));
//            rootPane.getChildren().setAll(pane);
            pbar.setProgress(0.0);
            send_button.setVisible(false);
            info_label.setVisible(false);
            msg_send.setVisible(false);
            msg_rcv.setVisible(false);
            for(int i=0;i<100;i++){
                pbar.setProgress(i/100.0);
                sleep(20);
            }
            pbar.setProgress(0.0);
            send_button.setVisible(true);
            info_label.setVisible(true);
            msg_send.setVisible(true);
            msg_rcv.setVisible(true);            
            pbar.setVisible(false);
                waitingLabel.setVisible(false);

            ss=new ServerSocket(8100);
            s=ss.accept();
            int ack = 0;
            in = new DataInputStream(System.in);
            inn = new DataInputStream(s.getInputStream());
            ps = new PrintStream(s.getOutputStream());        

            while (true)
            {
//                if (correct==0)
//                {
//                    System.out.println("Enter a Message: ");
//                    str = in.readLine();
//                }
                if (str.equalsIgnoreCase("fin"))
                {
                    ss.close();
                    break;
                }
                if(correct ==0 && str!=null){
                    ack = ack % 2;
                    ps.println(str);
                    str=null;
                }
                String str2 = inn.readLine();
                int reply=0;
                if (str2.equalsIgnoreCase("1") || str2.equalsIgnoreCase("2") || str2.equalsIgnoreCase("3") || str2.equalsIgnoreCase("4"))
                {
                    reply = Integer.parseInt(str2);
                }
                if (!str2.equalsIgnoreCase("fin"))
                {
                    if (reply==1) //operation with no loss
                    {
//                        System.out.println("Sender received a valid ACK for "+ack+" , send next message!");
                        msg_rcv.appendText("Sender received a valid ACK for "+ack+" , send next message!\n");
                        ack++;
                        correct=0;
                    }
                    if (reply==2) //Lost Packet
                    {
//                        System.out.println("Sender didn't recieve a ACK!");
                        msg_rcv.appendText("Sender didn't recieve a ACK!\n");
                        for (int i=0;i<5;i++)
                        {
                            msg_rcv.appendText("Waiting\n");
                        }
                        msg_rcv.appendText("Timeout! Sending Message Again\n");
                        correct++;
                    }
                    if (reply==3) //Lost ACK
                    {
                        msg_rcv.appendText("Sender received a corrupted ack (ACK is lost), keep waiting!\n");
                        for (int i=0;i<5;i++)
                        {
                            msg_rcv.appendText("Waiting\n");
                        }
                        msg_rcv.appendText("Timeout! Sending Message Again\n");
                        correct++;
                    }
                    if (reply==0 || reply==4) //Premature Timeout
                    {
                        if (reply==0)
                        {
                            msg_rcv.appendText("Sender didn't recieve a ACK because of Timeout!\n");
                            for (int i=0;i<5;i++)
                            {
                                msg_rcv.appendText("Waiting\n");
                            }
                            msg_rcv.appendText("Timeout! Sending Message Again\n");
                            correct++;
                        }
                        else if (reply==4)
                        {
                            msg_rcv.appendText("Sender received a valid ACK for "+ack+" , send next message!\n");
                            msg_rcv.appendText("Sender recieved a Duplicate ACK for "+ack+" , ACK ignored\n");
                            correct=0;
                            ack++;
                        }
                    }
                }
                else
                {
                    ss.close();
                    break;
                }
            }            

        } catch (Exception ex) {
            ex.printStackTrace();
        }



    }    

}

Now for running them i use this code:

Rdt_App.java:

package rdt_app;

import static java.lang.Thread.sleep;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author Dell
 */
public class Rdt_App extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

The errors i get :

Apr 14, 2018 3:59:54 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.101
java.lang.NullPointerException
    at rdt_app.FXMLDocumentController.initialize(FXMLDocumentController.java:114)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at rdt_app.Rdt_App.start(Rdt_App.java:24)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
halfer
  • 19,824
  • 17
  • 99
  • 186
Hammad97
  • 27
  • 7
  • Are you sure the code you posted and the stacktrace are from the same source in time? If I check the code the NPE would be at `if(correct ==0 && str!=null){` , which I find unlikely. For more help on NPEs you might read [What is a NullPointerException and how do I fix it](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – M. le Rutte Apr 14 '18 at 11:15
  • My bad. I did removed some commented code and lines in header . But here is full project link https://www.4shared.com/zip/Uf-0kwYKei/rdt_App.html . If anyone could help me there that would be highly appreciated. Thanks – Hammad97 Apr 14 '18 at 12:13

1 Answers1

0

Did you set your controller in your FXML document? If you don't set controller class for an FXML, FXML components never gets initialized and hence you get a NullPointerException. Besides you don't need to implement Initializable interface. Change @Override to @FXML for intialize () function.

Emre Dalkiran
  • 401
  • 3
  • 9
  • Yes, I made sure of that while creating FXML Document . Also, whenever i make any edits in ScreenBuilder i save it there and choose "Make Controller" option in Netbeans which even updates the target controller so that is not the issue i think. My whole project is here : https://www.4shared.com/zip/Uf-0kwYKei/rdt_App.html – Hammad97 Apr 14 '18 at 12:15
  • When do you get the error you posted above? I managed to create a gui as a standalone application from the code you mentioned. – Emre Dalkiran Apr 14 '18 at 15:00
  • So here's how it goes... When i run Rdt_App.java (Server) nothing pops up, then later as i run client.java (Client) server frame pops up and client doesnot come and it only comes when i close server frame. Error message i can see only when i close server application,not before that i guess that is because ss.accept(); is stuck waiting for client. – Hammad97 Apr 14 '18 at 15:19
  • Did you delete `implements Initializable` from your controller class? In addition to that, you have both client and server classes in the same project where both of them have `main` functions. I would suggest to create another project for the client. You are probably try to use same gui for both client and server. – Emre Dalkiran Apr 14 '18 at 15:35
  • Did you look at the stacktrace? It clearly indicates that the exception is thrown from the `initialize` method of the controller during loading the fxml file... Furthermore implementing `Initializable` may not be necessary but it certainly isn't incorrect. – fabian Apr 15 '18 at 01:44