getHostServices().showDocument() in a FXML File

后端 未结 1 478
遇见更好的自我
遇见更好的自我 2020-12-07 05:30

Is there any easy way to put into the toHomepage() method the getHostServices().showDocument() command somehow, instead of doing lines and lines of code, so the code should

1条回答
  •  粉色の甜心
    2020-12-07 06:06

    You need to pass the HostServices to the Controller.

    Key Code: Set the HostServices in the Controller.

    HostServices hostServices ;
    
    public void setGetHostController(HostServices hostServices)
    {
        this.hostServices = hostServices;
    }        
    

    Key Code: Passing HostServices to the Controller.

    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
    Parent root = loader.load();
    FXMLDocumentController fXMLDocumentController = loader.getController();
    fXMLDocumentController.setGetHostController(getHostServices());
    

    Main

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    /**
     *
     * @author sedrick
     */
    public class JavaFXApplication7 extends Application {
    
        @Override
        public void start(Stage stage) throws Exception {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
            Parent root = loader.load();
            FXMLDocumentController fXMLDocumentController = loader.getController();
            fXMLDocumentController.setGetHostController(getHostServices());
    
            Scene scene = new Scene(root);        
            stage.setScene(scene);
            stage.show();
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    
    }
    

    Controller

    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.application.HostServices;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.Label;
    
    /**
     *
     * @author sedri
     */
    public class FXMLDocumentController implements Initializable {
    
        HostServices hostServices;
    
        @FXML
        private Label label;
    
        @FXML
        private void handleButtonAction(ActionEvent event) {
            hostServices.showDocument("www.google.com");
        }
    
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            // TODO
        }    
    
        public void setGetHostController(HostServices hostServices)
        {
            this.hostServices = hostServices;
        }
    
    }
    

    FXML

    
    
    
    
    
    
    
    
    
        
            

    0 讨论(0)
提交回复
热议问题