FXML客户端 - 服务器GUI应用程序

时间:2018-04-14 11:03:23

标签: java nullpointerexception javafx-8 fxml

我曾经在Swing工作,但现在看到它已经过时了,JX8是Java应用程序的未来,所以我从ScreenBuilder的FXML GUI开始。并将我的RDT 3.0 TCP服务器 - 客户端代码集成到FXML GUI中。

但我有很多错误;我尝试解决了大部分问题但每次都得到nullPointerException并且我知道这是因为没有分配内存。我怎样才能摆脱它们,以及如何让我的应用程序运行?

以下是代码:

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(服务器):

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();
        }



    }    

}

现在运行它们我使用这段代码:

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);
    }

}

我得到的错误:

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)

1 个答案:

答案 0 :(得分:0)

您是否在FXML文档中设置了控制器?如果没有为FXML设置控制器类,FXML组件永远不会被初始化,因此你得到NullPointerException。此外,您不需要实现Initializable接口。 @Override功能将@FXML更改为intialize ()