JavaFx从另一个控制器调用另一个方法实例

时间:2020-06-28 12:02:40

标签: java javafx

我正在开发自动售货机的支付网关。我的网关使用套接字成功连接到自动售货机。我能够按要求的价格成功处理收到的消息,但是将批准消息发送回机器将得到java.lang.NullPointerException。我的UI在JavaFX上

下面是我在第一个控制器上的代码

@FXML
    public void handleButtonAction(ActionEvent event)throws UnknownHostException, IOException {
        LOGGER.info("Connect button Clicked"); 
        status.setWrapText(true);        
        status.appendText("Connect button Clicked \n");
        // getting localhost ip 
        InetAddress ip = InetAddress.getByName("localhost");        
          
        // establish the connection 
        s = new Socket(ip, ServerPort);
        status.appendText("connected to " + s.toString() + "\n" );
        LOGGER.info("connected to " +  s.toString() + "\n" );           
         
         //start a scanning thread
            receivemessage();         
    }

接收消息方法

public void receivemessage()
    {
         LOGGER.info("Receive message thread started"); 
         status.setWrapText(true);
         status.appendText("Receive message thread started \n");
        // readMessage thread 
        
        Thread readMessage = new Thread(new Runnable() 
        {
          // Platform.setImplicitExit(false); 
           
            public void run(){
                InputStream input = null;
                try {
                
                input = s.getInputStream();
                status.appendText("Scanning thread started.");

                //scanning always running
                while(true) {
                    
                    String dataString = ""; 
                    byte buffer[] = new byte[1024];
  
                    // read all received bytes
                    while (input.available() > 0) {
                        int i = input.read(buffer, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        dataString += new String(buffer, 0, i);
                    }
                    
                    if(!dataString.isEmpty()) {
                        status.appendText("Server respond: \"" +dataString +"\"");
                        LOGGER.info("Server respond: \"" +dataString +"\"");
                        
                        String VendRequest_input="External PC Plugin;Vend Request;add_on_variable=&required_price=50#";
                        try {
                            Thread.sleep(1000);       
                        } catch (InterruptedException ex) {
                            Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        final String data=dataString;
                        Platform.runLater(() ->{
                            try {
                                
                                loadPhoneInput(data);
                            } catch (IOException ex) {
                                Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        });
                        
                        
                         /*for (int x=0; x<result.length; x++) {
                            System.out.println(result[x]);
                            }*/
                        
                    }                       
                }
                
                } catch (IOException ex) {
                    Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                try {
                    input.close();
                } catch (IOException ex) {
                    Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
         }
        }); 
        
       readMessage.start();
    }
  
    public void loadPhoneInput( String dataString) throws IOException
    {
        
        //Parse String and Capture
        String Capture = dataString;
        String[] tokens = Capture.split("#");
        
        System.out.println(tokens.length);
        for(int i=0; i<tokens.length; i++)
        {
            String prefix = "External PC Plugin;Vend Request;add_on_variable=&required_price=";
            
            if(tokens[i].contains(prefix))
            {
                //fetch total Amount
                System.out.println(tokens[i]);
                String Command=tokens[i];
                String[] price = Command.split("&");
                String exact_Price=price[1]; //required_price=50
                String[] total_Amount =exact_Price.split("=");
                System.out.println();
                String totalAmount=total_Amount[1];
                //Load phone Input and Pass Prices
                FXMLLoader loader = new FXMLLoader(getClass().getResource("PhoneInput.fxml"));
                Parent root = (Parent) loader.load();
                //transfer totalAmount
                PhoneInputController phonecontoller=loader.<PhoneInputController>getController();
                phonecontoller.setDispenseAmount(totalAmount);
                //load phone input
                Stage stage=new Stage();
                Scene scene = new Scene(root);        
                stage.setScene(scene);
                stage.initStyle(StageStyle.UNDECORATED);
                stage.show(); 
                stage.centerOnScreen();
                stage.setAlwaysOnTop(true);
                //close current pane
                //ConnectorStage = (Stage)ConnectorPane.getScene().getWindow();// pane you are ON
                //ConnectorStage.hide();
            }            
        }        
    }

发送批准消息方法

@FXML
public void sendVendronApproveResponse() 
{
    System.out.println("Sending Initiated....");
    String msg ="External PC Plugin;Vend Request Respond;status=approve#";
    try {
        PrintWriter output= new PrintWriter(s.getOutputStream(),true);
        output.printf(msg);
        output.flush();
        status.appendText("\nSending to server: " +msg);
    } catch (Exception e) {
       LOGGER.info(e.toString());
       e.printStackTrace();
       System.out.println( e.getCause());
    }
}

这是第二个控制器调用发送消息时的代码

private  void postUsingRawJSON(WebTarget target) throws IOException {
        
        String payment = paymentUtil.createPaymentInJSON(phoneNumberInput
                  , amountInput
                  , "1");
       
        ProviderResponse response = target.request()
                  .post(Entity.entity(payment, MediaType.APPLICATION_JSON)
                            , ProviderResponse.class);
        System.out.println(response.getCode());
        
        //Response message option to Vendron
        String Vend_Request_Respond_APPROVE="External PC Plugin;Vend Request Respond;status=approve#";
        String Vend_Request_Respond_DENIED="External PC Plugin;Vend Request Respond;status=denied#";
        
        String code=response.getCode();
        switch (code){
            case "0":
            {
            //send Vendron Dispense Command
            try 
            {                
            FXMLLoader loader1 = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
            BritsConnectController britsContoller = loader1.getController();
            britsContoller.sendMessage(Vend_Request_Respond_APPROVE);
            }            
            catch (Exception ex) {
            ex.getCause();
            ex.printStackTrace();
            }
                
            FXMLLoader loader = new FXMLLoader(getClass().getResource("successTransaction.fxml"));
            Parent root = loader.load();
            Stage stage=new Stage();
            Scene scene = new Scene(root);        
            stage.setScene(scene);
            stage.initStyle(StageStyle.UNDECORATED);
            stage.show(); 
            stage.centerOnScreen();
            stage.setAlwaysOnTop(true);
            confirmStage = (Stage)confirmPane.getScene().getWindow();// pane you are ON
            confirmStage.hide();
            
           
            
            PauseTransition delay = new PauseTransition(Duration.seconds(10));
            delay.setOnFinished( event -> stage.close() );
            delay.play();
            break;
            }
            
           
                
        }
        //get the new customer
        //getCustomerById(target, response);

    }

0 个答案:

没有答案
相关问题