Java javafx.scene.web.WebView 代码实例

・21 分钟阅读

以下是展示如何使用javafx.scene.web.WebView的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void setClient(WebView view) {
        this.view = view;
        this.engine = view.getEngine();
        JSObject window = (JSObject) engine.executeScript("window");
        window.setMember("ide", this);
        onLoadFunctions = new ArrayList<IEclipseToBrowserFunction>();
        currentUrl = view.getEngine().locationProperty().get();
        //Need to remove any query parameters that might break pattern matching for extensions
        currentUrl = StringUtils.substringBeforeLast(currentUrl, "?");
        currentUrl = StringUtils.substringBeforeLast(currentUrl, "&");
        loadInitialFunctions();
}
 

实例 2


private void initChatView() {
  WebView messagesWebView = getMessagesWebView();
  JavaFxUtil.configureWebView(messagesWebView, preferencesService);
  messagesWebView.addEventHandler(MouseEvent.MOUSE_MOVED, moveHandler);
  messagesWebView.zoomProperty().addListener((observable, oldValue, newValue) -> {
    preferencesService.getPreferences().getChat().setZoom(newValue.doubleValue());
    preferencesService.storeInBackground();
  });
  Double zoom = preferencesService.getPreferences().getChat().getZoom();
  if (zoom != null) {
    messagesWebView.setZoom(zoom);
  }
  engine = messagesWebView.getEngine();
  ((JSObject) engine.executeScript("window")).setMember(CHAT_TAB_REFERENCE_IN_JAVASCRIPT, this);
  engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
    if (Worker.State.SUCCEEDED.equals(newValue)) {
      synchronized (waitingMessages) {
        waitingMessages.forEach(this::appendMessage);
        waitingMessages.clear();
        isChatReady = true;
      }
    }
  });
  try (InputStream inputStream = CHAT_HTML_RESOURCE.getInputStream()) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ByteCopier.from(inputStream).to(byteArrayOutputStream).copy();
    String chatContainerHtml = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)
        .replace("{chat-container-js}", CHAT_JS_RESOURCE.getURL().toExternalForm())
        .replace("{auto-linker-js}", AUTOLINKER_JS_RESOURCE.getURL().toExternalForm());
    engine.loadContent(chatContainerHtml);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 

实例 3


/**
 * Creates a new map view and specifies if the FireBug pane should be
 * displayed in the WebView
 *
 * @param mapResourcePath
 * @param debug true if the FireBug pane should be displayed in the WebView.
 */
public GoogleMapView(String mapResourcePath, boolean debug) {
    String htmlFile;
    if (mapResourcePath == null) {
        if (debug) {
            htmlFile = "/html/maps-debug.html";
        } else {
            htmlFile = "/html/maps.html";
        }
    } else {
        htmlFile = mapResourcePath;
    }
    webview = new WebView();
    webengine = new JavaFxWebEngine(webview.getEngine());
    JavascriptRuntime.setDefaultWebEngine(webengine);
    setTopAnchor(webview, 0.0);
    setLeftAnchor(webview, 0.0);
    setBottomAnchor(webview, 0.0);
    setRightAnchor(webview, 0.0);
    getChildren().add(webview);
    webview.widthProperty().addListener(e -> mapResized());
    webview.heightProperty().addListener(e -> mapResized());
    webview.widthProperty().addListener(e -> mapResized());
    webview.heightProperty().addListener(e -> mapResized());
    webengine.getLoadWorker().stateProperty().addListener(
            new ChangeListener<Worker.State>() {
                public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
                    if (newState == Worker.State.SUCCEEDED) {
                        setInitialized(true);
                        fireMapInitializedListeners();
                    }
                }
            });
    webengine.load(getClass().getResource(htmlFile).toExternalForm());
}
 

实例 4


protected WebView getWebView() {
        if (engine == null) {
                webView = new WebView();
                webView.setContextMenuEnabled(false);
                engine = webView.getEngine();
        }
        return webView;
}
 

实例 5


public InfoController(String title, String url) {
    this.title = title;
    this.url = url;
    // Set view
    registerFXML("gui/help_function.fxml");
    //view.fxmlPane.setOnKeyReleased(this::keypressHandler);
    headerTitle.setText(this.title);
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    contentHolder.setTopAnchor(browser, 0.0);
    contentHolder.setBottomAnchor(browser, 0.0);
    contentHolder.setLeftAnchor(browser, 0.0);
    contentHolder.setRightAnchor(browser, 0.0);
    contentHolder.getChildren().add(browser);
    webEngine.load(this.url);
    exitButton.setOnAction(this::cancelHandler);
}
 

实例 6


@Override
public void start(Stage stage) throws Exception {
    TabPane tabPane = new TabPane();
    Tab tab1 = new Tab();
    tab1.setText("Demos");
    tab1.setClosable(false);
    SplitPane sp = new SplitPane();
    final StackPane sp1 = new StackPane();
    sp1.getChildren().add(createTreeView());
    final BorderPane sp2 = new BorderPane();
    sp2.setCenter(createChartPane());
    sp.getItems().addAll(sp1, sp2);
    sp.setDividerPositions(0.3f, 0.6f);
    tab1.setContent(sp);
    tabPane.getTabs().add(tab1);        
    Tab tab2 = new Tab();
    tab2.setText("About");
    tab2.setClosable(false);
    WebView browser = new WebView();
    WebEngine webEngine = browser.getEngine();
    webEngine.load(getClass().getResource("/com/orsoncharts/demo/about.html").toString());
    tab2.setContent(browser);
    tabPane.getTabs().add(tab2);        
    Scene scene = new Scene(tabPane, 1024, 768);
    stage.setScene(scene);
    stage.setTitle("Orson Charts JavaFX Demo");
    stage.show();
}
 

实例 7


/**
 * Builds the browser based on the given url .
 * @param url the URL of the website to be snapshotted.
 * @param controller
 */
public Snapshotter(String url, String padPath, MainController controller){
    this.url = url;
    this.padPath = padPath;
    this.controller = controller;
    urlStage = new Stage();
    browser = new WebView();
    webEngine = browser.getEngine();
    screenSize = Screen.getPrimary().getVisualBounds();
    setupUI();
}
 

实例 8


public SimpleBrowserImpl(Stage stage, String url) throws IOException {
        super () ;
        Preconditions.checkNotNull(stage) ;
        this.stage = stage ;
        stage.setTitle("Drive Uploader - Authentication");
        UiUtils.setStageAppSize(stage) ;
        Scene scene = new Scene(new Group());
        AnchorPane root = new AnchorPane () ;  
        final WebView browser = new WebView();
        webEngine = browser.getEngine();
        /*
        Menu settingsMenu = new Menu ("Settings") ;
        MenuItem proxy = new MenuItem ("Proxy") ;
        settingsMenu.getItems().add(proxy) ;
        MenuBar menuBar = new MenuBar () ;
        menuBar.getMenus().add(settingsMenu) ;
        proxy.setOnAction(new EventHandler<ActionEvent> () {
                        @Override
                        public void handle(ActionEvent event) {
                                try {
                                        ProxySettingDialog dlg = new ProxySettingDialog (stage, Configuration.INSTANCE) ;
                                        dlg.showDialog();
                                } catch (IOException e) {
                                        logger.error("Error occurred while opening the proxy setting dialog", e);
                                }
                        }});*/
                FXMLLoader mainMenuLoader = new FXMLLoader(getClass().getResource("/fxml/MainMenu.fxml")); 
                VBox mainMenuBar = (VBox)mainMenuLoader.load() ;
                AnchorPane.setTopAnchor(mainMenuBar, 0.0);
                AnchorPane.setLeftAnchor(mainMenuBar, 0.0);
                AnchorPane.setRightAnchor(mainMenuBar, 0.0);
                MainMenuController mainMenuController = mainMenuLoader.<MainMenuController>getController();
                mainMenuController.setOwner(stage) ;
                mainMenuController.setConfiguration(Configuration.INSTANCE) ;
                mainMenuController.hideAccountMenu(true);
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(browser);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        if (StringUtils.isNotEmpty(url)) {
                goTo (url) ;
        }
        if (DriveUploader.isMacOsX()) {
                AnchorPane.setTopAnchor(scrollPane, 5.0) ;
        } else {
                AnchorPane.setTopAnchor(scrollPane, 35.0) ;
        }
        AnchorPane.setLeftAnchor(scrollPane, 5.0) ;
        AnchorPane.setRightAnchor(scrollPane, 5.0) ;
        AnchorPane.setBottomAnchor(scrollPane, 5.0) ;
        root.getChildren().add(mainMenuBar) ;
        root.getChildren().addAll(scrollPane);
        scene.setRoot(root);
        stage.setScene(scene);
    }
 

实例 9


private Void initWeb(CountDownLatch latch, JFXPanel jfxPanel,String html){
Group root = new Group();  
Scene scene = new Scene(root);  
WebView browser = new WebView();
this.webEngine = browser.getEngine();
this.webEngine.getLoadWorker().stateProperty().addListener(
  (ov, oldState,newState)->{
    if (newState == Worker.State.SUCCEEDED) {latch.countDown();}
    });
this.webEngine.loadContent(html);
this.webEngine.setOnAlert(event->{         
  Alert alert = new Alert(AlertType.INFORMATION);
  alert.setTitle("Information Dialog");
  alert.setHeaderText(null);
  alert.setContentText(event.getData());
  alert.showAndWait();
  //alert.setOnCloseRequest(e->{  alert.close(); });
  });        
root.getChildren().add(browser);                     
jfxPanel.setScene(scene);
return null;
}
 

实例 10


private Scene createScene() {
    view = new WebView();
    engine = view.getEngine();
    engine.load(this.getClass().getResource("map.html").toExternalForm());
    Scene scene = new Scene(view);
    return scene;
}
 

实例 11


@Override
    public void start(Stage stage) {
        BorderPane bp = new BorderPane();
        // Load text field with default text (the start page URL)
        TextField location = new TextField(startPage);
        Button launch = new Button("go");
        HBox toolbar = new HBox(20, location, launch);
        toolbar.setPrefHeight(40);
        toolbar.setAlignment(Pos.BOTTOM_CENTER);
        bp.setTop(toolbar);
        WebView webView = new WebView();
        bp.setCenter(webView);
        WebEngine engine = webView.getEngine();
        engine.load(startPage);
        Worker loadWorker = engine.getLoadWorker();
        loadWorker.stateProperty().addListener(e -> {
            Worker.State state = loadWorker.getState();
            if (state == Worker.State.RUNNING) {
                launch.setDisable(true);
            } else {
                launch.setDisable(false);
            }
//            System.out.println("new state for worker = " + loadWorker.getState());
        });
        launch.setOnAction(e -> {
            String resolved = resolveLocation(location.getText());
            engine.load(resolved);
        });
        Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
        Scene scene = new Scene(bp, visualBounds.getWidth(), visualBounds.getHeight());
        stage.setScene(scene);
        stage.show();
    }
 

实例 12


/**
 * Intializes the WebView with a specific redirect URL and client.
 *
 * @param applicationContext not used
 * @param clientId           client ID to use when authenticating with the API
 * @param clientSecret       client secret to use when authenticating with the API
 * @param redirectUrl        redirect URL to use with OAuth
 * @param boxClient          client to authenticate
 */
@Override
public void initializeAuthFlow(Object applicationContext, String clientId, String clientSecret, String redirectUrl,
    BoxClient boxClient) {
    mWebViewData = new OAuthWebViewData(boxClient.getOAuthDataController());
    if (StringUtils.isNotEmpty(redirectUrl)) {
        mWebViewData.setRedirectUrl(redirectUrl);
    }
    webView = new WebView();
    webView.setMinSize(minWidth, minHeight);
    webView.setMaxSize(maxWidth, maxHeight);
    webEngine = webView.getEngine();
    webEngine.setJavaScriptEnabled(true);
    webEngine.setOnStatusChanged(createEventHandler());
}
 

实例 13


@Override
public void init() {
    setPrefWidth(300);
    setPrefHeight(300);
    final WebView webView = new WebView();
    Rectangle clipRect = new Rectangle();
    clipRect.setWidth(300);
    clipRect.setHeight(300);
    clipRect.setArcHeight(20);
    clipRect.setArcWidth(20);
    clipRect.setLayoutX(10);
    clipRect.setLayoutY(10);
    webView.setClip(clipRect);
    final WebEngine webEngine = webView.getEngine();
    URL url = getClass().getResource("/weather2.html");
    System.out.println(url);
    String fileText = url.toExternalForm();
    webEngine.load(fileText);
    Group grp = new Group(webView);
    getChildren().add(grp);
}
 

实例 14


@Override
public void init() {
    setPrefWidth(300);
    setPrefHeight(300);
    final WebView webView = new WebView();
    Rectangle clipRect = new Rectangle();
    clipRect.setWidth(300);
    clipRect.setHeight(300);
    clipRect.setArcHeight(20);
    clipRect.setArcWidth(20);
    clipRect.setLayoutX(10);
    clipRect.setLayoutY(10);
    webView.setClip(clipRect);
    final WebEngine webEngine = webView.getEngine();
    URL url = getClass().getResource("/weather2.html");
    System.out.println(url);
    String fileText = url.toExternalForm();
    webEngine.load(fileText);
    Group grp = new Group(webView);
    getChildren().add(grp);
}
 

实例 15


protected void build() throws IOException {
        stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.centerOnScreen();
        stage.setTitle(title);
        webView = new WebView();
        WebEngine e = webView.getEngine();
        //Remove logging from WebView renderer. It messes things up if you don't.
        //If the logging is set to something higher than FINEST, which it appears to be by default,
        //WebView enters a debugging mode.
        java.util.logging.Logger.getLogger(WCGraphicsPrismContext.class.getName()).setLevel(java.util.logging.Level.OFF);  
        root = new VBox();
        BufferedReader reader = new BufferedReader(new InputStreamReader(LicenseView.class.getClassLoader().getResourceAsStream(file)));
        String line;
        StringBuilder output = new StringBuilder();
        Font.loadFont(
                LicenseView.class.getClassLoader().getResource("Lato-Regular.ttf").toExternalForm(), 
                12
        );
        while ((line = reader.readLine()) != null) {
                if (line.startsWith("<head>")) {
                        String style = FileHelper.fileToString(LicenseView.class.getClassLoader().getResourceAsStream("theme_web_base.css")) + "n" +
                                                   FileHelper.fileToString(LicenseView.class.getClassLoader().getResourceAsStream("theme_web_green.css")); //TODO Theme from settings
                        output.append(line.replace("<head>", "<head><style>" + style + "</style>"));
                } else {
                        output.append(line);
                }
                output.append(" ");
        }
        e.loadContent(output.toString());
        closeButton = new Button();
        closeButton.setId("message-dialogue-button");
        closeButton.setPrefWidth(120);
        closeButton.setMinHeight(40);
        closeButton.setPrefHeight(40);
        closeButton.setAlignment(Pos.CENTER);
        closeButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(final ActionEvent event) {
                        controller.close();
                }
        });
        root.getChildren().addAll(
                webView,
                closeButton
        );
        root.setAlignment(Pos.CENTER);
        VBox.setMargin(closeButton, new Insets(25, 0, 20, 0));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(MessageDialogue.class.getClassLoader().getResource("theme_base.css").toExternalForm());
        scene.getStylesheets().add(MessageDialogue.class.getClassLoader().getResource(settings.getPropertyString("theme")).toExternalForm());
        stage.setScene(scene);
        stage.setWidth(700);
        stage.setMinWidth(700);
        stage.setMinHeight(600);
        updateStrings();
}
 
讨论
淘淘あ西西 profile image