Java Code Examples for javafx.scene.web.WebEngine#load()

The following examples show how to use javafx.scene.web.WebEngine#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TextEditorPane.java    From logbook-kai with MIT License 6 votes vote down vote up
@FXML
void initialize() {
    WebEngine engine = this.webview.getEngine();
    engine.load(PluginServices.getResource("logbook/gui/text_editor_pane.html").toString());
    engine.getLoadWorker().stateProperty().addListener(
            (ob, o, n) -> {
                if (n == Worker.State.SUCCEEDED) {
                    this.setting();
                }
            });

    KeyCombination copy = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN);
    KeyCombination cut = new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN);

    this.webview.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (copy.match(event) || cut.match(event)) {
            String text = String.valueOf(engine.executeScript("getCopyText()"));

            Platform.runLater(() -> {
                ClipboardContent content = new ClipboardContent();
                content.putString(text);
                Clipboard.getSystemClipboard().setContent(content);
            });
        }
    });
}
 
Example 2
Source File: IndexService.java    From xJavaFxTool-spring with Apache License 2.0 6 votes vote down vote up
/**
 * @Title: addWebView
 * @Description: 添加WebView视图
 */
public void addWebView(String title, String url, String iconPath) {
    WebView browser = new WebView();
    WebEngine webEngine = browser.getEngine();
    if (url.startsWith("http")) {
        webEngine.load(url);
    } else {
        webEngine.load(IndexController.class.getResource(url).toExternalForm());
    }
    if (indexController.getSingleWindowBootCheckBox().isSelected()) {
        JavaFxViewUtil.getNewStage(title, iconPath, new BorderPane(browser));
        return;
    }
    Tab tab = new Tab(title);
    if (StringUtils.isNotEmpty(iconPath)) {
        ImageView imageView = new ImageView(new Image(iconPath));
        imageView.setFitHeight(18);
        imageView.setFitWidth(18);
        tab.setGraphic(imageView);
    }
    tab.setContent(browser);
    indexController.getTabPaneMain().getTabs().add(tab);
    indexController.getTabPaneMain().getSelectionModel().select(tab);
}
 
Example 3
Source File: Browser.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
public void loadPage(TextField textField, //ProgressBar progressBar,
		WebEngine webEngine, WebView webView) {

	String route = textField.getText();
	if (route !=null)
		if (!route.substring(0, 7).equals("http://")) {
			route = "http://" + route;
			textField.setText(route);
		}

	System.out.println("Loading route: " + route);
	//progressBar.progressProperty().bind(webEngine.getLoadWorker().progressProperty());

	webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
		@Override
		public void changed(ObservableValue<? extends State> value,
				State oldState, State newState) {
			if(newState == State.SUCCEEDED){
				System.out.println("Location loaded + " + webEngine.getLocation());
			}
		}
	});
	webEngine.load(route);


}
 
Example 4
Source File: UpdateDialogController.java    From updatefx with MIT License 6 votes vote down vote up
private void initialize() {
	URL changelog = release.getApplication().getChangelog();
	
	if (changelog != null) {
		WebEngine engine = changeView.getEngine();
		String finalURL = String.format("%s?from=%d&to=%d", changelog, currentReleaseID, release.getId());
		engine.load(finalURL);
	} else {
		changeView.setVisible(false);
		changeView.setManaged(false);
	}
	
   Object[] messageArguments = { release.getApplication().getName(), currentVersion, release.getVersion() };
   MessageFormat formatter = new MessageFormat("");
   formatter.setLocale(resources.getLocale());
   
	if (release.getLicenseVersion() != currentLicenseVersion) {
		formatter.applyPattern(resources.getString("infotext.paidupgrade"));
	} else {
		formatter.applyPattern(resources.getString("infotext.freeupgrade"));			
	}
	
	infoLabel.setText(formatter.format(messageArguments));
	infoLabel.autosize();
}
 
Example 5
Source File: WebViewDemo.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start(Stage primaryStage) {

    StackPane root = new StackPane();
    WebView x = new WebView();
    WebEngine ex = x.getEngine();
    ex.load("https://github.com/travis-ci/travis-ci");

    root.getChildren().add(x);
    java.net.CookieHandler.setDefault(null);
    Scene scene = new Scene(root, 1024, 768);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}
 
Example 6
Source File: OrsonChartsFXDemo.java    From jfree-fxdemos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private SplitPane createChartPane() {
    CategoryDataset3D dataset = SampleData.createCompanyRevenueDataset();
    Chart3D chart = AreaChart3DFXDemo1.createChart(dataset);
    Chart3DViewer viewer = new Chart3DViewer(chart);
  
    this.splitter = new SplitPane();
    splitter.setOrientation(Orientation.VERTICAL);
    final BorderPane borderPane = new BorderPane();
    borderPane.setCenter(viewer);
    
   // Bind canvas size to stack pane size.
    viewer.prefWidthProperty().bind(borderPane.widthProperty());
    viewer.prefHeightProperty().bind(borderPane.heightProperty());

    final StackPane sp2 = new StackPane();
    
    this.chartDescription = new WebView();
    WebEngine webEngine = chartDescription.getEngine();
    webEngine.load(AreaChart3DFXDemo1.class.getResource("AreaChart3DFXDemo1.html").toString());
    
    sp2.getChildren().add(chartDescription);  
    splitter.getItems().addAll(borderPane, sp2);
    splitter.setDividerPositions(0.70f, 0.30f);
    return splitter;
}
 
Example 7
Source File: POB_webviewController.java    From Path-of-Leveling with MIT License 5 votes vote down vote up
public void open(String url){
    //final WebEngine webEngine = pob.getEngine();
    WebEngine engine = pob.getEngine();
    engine.load(url);
    /*
    Hyperlink hpl = new Hyperlink(url);
    
    hpl.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent e) {
          webEngine.load(url);
      }
  });*/
}
 
Example 8
Source File: OrsonChartsFXDemo.java    From jfree-fxdemos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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("/org/jfree/chart3d/fx/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();
}
 
Example 9
Source File: ACEEditor.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void initComponent() {
    webView = new WebView();
    String externalForm = ACEEditor.class.getResource("/Ace.html").toExternalForm();
    WebEngine engine = webView.getEngine();
    engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
        @Override
        public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
            if (newValue != State.SUCCEEDED) {
                return;
            }
            JSObject window = (JSObject) engine.executeScript("window");
            window.setMember("java", ACEEditor.this);
            engine.executeScript("console.log = function(message)\n" + "{\n" + "    java.log(message);\n" + "};");
            ACEEditor.this.engine = engine;
            setOptions(new JSONObject().put("showLineNumbers", showLinenumbers).put("firstLineNumber", startLineNumber)
                    .put("overwrite", false));
            loadPreferences();
            hookKeyBindings();
        }
    });
    engine.load(externalForm);
    ToolBarContainer container = ToolBarContainer.createDefaultContainer(Orientation.RIGHT);
    if (withToolbar) {
        ToolBarPanel toolBarPanel = container.getToolBarPanel();
        createToolBars(toolBarPanel);
    }
    container.setContent(webView);
    this.node = container;
}
 
Example 10
Source File: WebViewSample.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public WebViewSample() {
    WebView webView = new WebView();
    
    final WebEngine webEngine = webView.getEngine();
    webEngine.load(DEFAULT_URL);
    
    final TextField locationField = new TextField(DEFAULT_URL);
    webEngine.locationProperty().addListener(new ChangeListener<String>() {
        @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            locationField.setText(newValue);
        }
    });
    EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent event) {
            webEngine.load(locationField.getText().startsWith("http://") 
                    ? locationField.getText() 
                    : "http://" + locationField.getText());
        }
    };
    locationField.setOnAction(goAction);
    
    Button goButton = new Button("Go");
    goButton.setDefaultButton(true);
    goButton.setOnAction(goAction);
    
    // Layout logic
    HBox hBox = new HBox(5);
    hBox.getChildren().setAll(locationField, goButton);
    HBox.setHgrow(locationField, Priority.ALWAYS);
    
    VBox vBox = new VBox(5);
    vBox.getChildren().setAll(hBox, webView);
    VBox.setVgrow(webView, Priority.ALWAYS);

    getChildren().add(vBox);
}
 
Example 11
Source File: WebViewBrowser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public WebViewPane() {
    VBox.setVgrow(this, Priority.ALWAYS);
    setMaxWidth(Double.MAX_VALUE);
    setMaxHeight(Double.MAX_VALUE);

    WebView view = new WebView();
    view.setMinSize(500, 400);
    view.setPrefSize(500, 400);
    final WebEngine eng = view.getEngine();
    eng.load("http://www.oracle.com/us/index.html");
    final TextField locationField = new TextField("http://www.oracle.com/us/index.html");
    locationField.setMaxHeight(Double.MAX_VALUE);
    Button goButton = new Button("Go");
    goButton.setDefaultButton(true);
    EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent event) {
            eng.load(locationField.getText().startsWith("http://") ? locationField.getText() :
                    "http://" + locationField.getText());
        }
    };
    goButton.setOnAction(goAction);
    locationField.setOnAction(goAction);
    eng.locationProperty().addListener(new ChangeListener<String>() {
        @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            locationField.setText(newValue);
        }
    });
    GridPane grid = new GridPane();
    grid.setVgap(5);
    grid.setHgap(5);
    GridPane.setConstraints(locationField, 0, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
    GridPane.setConstraints(goButton,1,0);
    GridPane.setConstraints(view, 0, 1, 2, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
    grid.getColumnConstraints().addAll(
            new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true),
            new ColumnConstraints(40, 40, 40, Priority.NEVER, HPos.CENTER, true)
    );
    grid.getChildren().addAll(locationField, goButton, view);
    getChildren().add(grid);
}
 
Example 12
Source File: WebBrowser.java    From yfiton with Apache License 2.0 4 votes vote down vote up
@Override
public void start(final Stage stage) throws Exception {
    // required to allow CORS
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

    BorderPane borderPane = new BorderPane();

    WebView browser = new WebView();
    WebEngine webEngine = browser.getEngine();
    webEngine.setUserAgent("Yfiton");

    Map<String, String> parameters = getParameters().getNamed();
    borderPane.setCenter(browser);
    webEngine.documentProperty().addListener((prop, oldDoc, newDoc) -> {
        String debugMode = parameters.get("debug");
        if (debugMode != null && debugMode.equalsIgnoreCase("true")) {
            enableFirebug(webEngine);
        }
    });
    webEngine.load(parameters.get("authorization-url"));

    Class<?> listenerClass = Class.forName(parameters.get("webengine-listener-class"));

    WebEngineListener listener =
            (WebEngineListener) listenerClass.getConstructor(
                    WebEngine.class, String.class, String.class).newInstance(
                    webEngine, parameters.get("authorization-file"), parameters.get("authorization-code-parameter-name"));

    webEngine.getLoadWorker().stateProperty().addListener(listener);

    stage.setTitle("Yfiton");

    Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();

    scene =
            new Scene(
                    borderPane,
                    primaryScreenBounds.getWidth() * 0.55,
                    primaryScreenBounds.getHeight() * 0.65);

    stage.setScene(scene);
    stage.getIcons().add(new Image(this.getClass().getResourceAsStream("/yfiton-icon.png")));
    stage.show();
    stage.setOnCloseRequest(event -> System.exit(EXIT_CODE_ON_CLOSE));
}
 
Example 13
Source File: MainViewImpl.java    From oim-fx with MIT License 4 votes vote down vote up
protected void initComponent() {

		Image normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_contacts_normal.png");
		Image hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_contacts_hover.png");
		Image selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_contacts_selected.png");

		mainFrame.addTab(normalImage, hoverImage, selectedImage, userRoot);

		normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_group_normal.png");
		hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_group_hover.png");
		selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_group_selected.png");

		mainFrame.addTab(normalImage, hoverImage, selectedImage, groupRoot);

		normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_last_normal.png");
		hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_last_hover.png");
		selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/icon_last_selected.png");

		mainFrame.addTab(normalImage, hoverImage, selectedImage, lastRoot);

		normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/qzone_normal.png");
		hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/qzone_hover.png");
		selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/qzone_selected.png");

		VBox website = new VBox();
		WebView websiteWebView = new WebView();
		WebEngine websiteWebEngine = websiteWebView.getEngine();
		websiteWebEngine.load("http://www.oimismine.com/");
		website.getChildren().add(websiteWebView);

		mainFrame.addTab(normalImage, hoverImage, selectedImage, website);

		normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_tab_inco_normal.png");
		hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_tab_inco_hover.png");
		selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_tab_inco_selected.png");

		VBox blog = new VBox();
		WebView blogWebView = new WebView();
		WebEngine blogWebEngine = blogWebView.getEngine();
		blogWebEngine.load("https://my.oschina.net/onlyxiahui/blog/759149");
		blog.getChildren().add(blogWebView);
		// blog.setStyle("-fx-background-color:rgba(215, 165, 230, 1)");
		mainFrame.addTab(normalImage, hoverImage, selectedImage, blog);

		normalImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_phone_inco_normal.png");
		hoverImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_phone_inco_hover.png");
		selectedImage = ImageBox.getImageClassPath("/resources/main/images/panel/main_panel_phone_inco_selected.png");

		VBox git = new VBox();

		WebView gitWebView = new WebView();
		WebEngine gitWebEngine = gitWebView.getEngine();
		gitWebEngine.load("https://gitee.com/onlysoftware/oim-fx");

		git.getChildren().add(gitWebView);
		// git.setStyle("-fx-background-color:rgba(112, 245, 86, 1);");
		mainFrame.addTab(normalImage, hoverImage, selectedImage, git);
	}
 
Example 14
Source File: O365InteractiveAuthenticatorFrame.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
private void initFX(final JFXPanel fxPanel, final String url, final String redirectUri) {
    WebView webView = new WebView();
    final WebEngine webViewEngine = webView.getEngine();

    final ProgressBar loadProgress = new ProgressBar();
    loadProgress.progressProperty().bind(webViewEngine.getLoadWorker().progressProperty());

    StackPane hBox = new StackPane();
    hBox.getChildren().setAll(webView, loadProgress);
    Scene scene = new Scene(hBox);
    fxPanel.setScene(scene);

    webViewEngine.setOnAlert(stringWebEvent -> SwingUtilities.invokeLater(() -> {
        String message = stringWebEvent.getData();
        JOptionPane.showMessageDialog(O365InteractiveAuthenticatorFrame.this, message);
    }));
    webViewEngine.setOnError(event -> LOGGER.error(event.getMessage()));


    webViewEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
        if (newState == Worker.State.SUCCEEDED) {
            loadProgress.setVisible(false);
            location = webViewEngine.getLocation();
            updateTitleAndFocus(location);
            LOGGER.debug("Webview location: " + location);
            // override console.log
            O365InteractiveJSLogger.register(webViewEngine);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(dumpDocument(webViewEngine.getDocument()));
            }
            if (location.startsWith(redirectUri)) {
                LOGGER.debug("Location starts with redirectUri, check code");

                authenticator.isAuthenticated = location.contains("code=") && location.contains("&session_state=");
                if (!authenticator.isAuthenticated && location.contains("error=")) {
                    authenticator.errorCode = location.substring(location.indexOf("error="));
                }
                if (authenticator.isAuthenticated) {
                    LOGGER.debug("Authenticated location: " + location);
                    String code = location.substring(location.indexOf("code=") + 5, location.indexOf("&session_state="));
                    String sessionState = location.substring(location.lastIndexOf('='));

                    LOGGER.debug("Authentication Code: " + code);
                    LOGGER.debug("Authentication session state: " + sessionState);
                    authenticator.code = code;
                }
                close();
            }
        } else if (newState == Worker.State.FAILED) {
            Throwable e = webViewEngine.getLoadWorker().getException();
            if (e != null) {
                handleError(e);
            }
            close();
        }

    });
    webViewEngine.load(url);
}
 
Example 15
Source File: WebFrame.java    From oim-fx with MIT License 4 votes vote down vote up
public void load(String url){
	WebEngine webEngine = webView.getEngine();
	webEngine.load(url);
}
 
Example 16
Source File: HelloWebView.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
@Override
    public void start(Stage stage) {
        List<String> args = getParameters().getRaw();
        final String initialURL = args.size() > 0 ? args.get(0) : DEFAULT_URL;

        final WebView webView = new WebView();
    	final WebEngine webEngine = webView.getEngine();

        final TextField urlBox = new TextField();
        urlBox.setMinHeight(NAVI_BAR_MIN_DIMENSION);

        urlBox.setText(initialURL);
        HBox.setHgrow(urlBox, Priority.ALWAYS);
        urlBox.setOnAction(e -> webEngine.load(urlBox.getText()));

//-        Button goButton = new Button("Go");
//-        goButton.setOnAction(e -> webEngine.load(urlBox.getText()));
        final Label bottomTitle = new Label();
        bottomTitle.textProperty().bind(urlBox.textProperty());

//-        HBox naviBar = new HBox();
//-        naviBar.getChildren().addAll(urlBox, goButton);
        final Button goStopButton = new Button(goButtonUnicodeSymbol);
        goStopButton.setStyle(buttonStyle);
        goStopButton.setOnAction(e -> webEngine.load(urlBox.getText()));

//-        BorderPane root = new BorderPane();
//-        root.setTop(naviBar);
//-        root.setCenter(webView);
        final Button backButton = new Button(backButtonUnicodeSymbol);
        backButton.setStyle(buttonStyle);
        backButton.setDisable(true);
        backButton.setOnAction(e -> webEngine.getHistory().go(-1));

//-        webEngine.locationProperty().addListener((obs, oVal, nVal)
//-                -> urlBox.setText(nVal));
        final Button forwardButton = new Button(forwardButtonUnicodeSymbol);
        forwardButton.setStyle(buttonStyle);
        forwardButton.setDisable(true);
        forwardButton.setOnAction(e -> webEngine.getHistory().go(+1));

        final Button reloadButton = new Button(reloadButtonUnicodeSymbol);
        reloadButton.setStyle(buttonStyle);
        reloadButton.setOnAction(e -> webEngine.reload());

        final HBox naviBar = new HBox();
        naviBar.getChildren().addAll(backButton, forwardButton, urlBox,
                reloadButton, goStopButton);
        naviBar.setPadding(new Insets(PADDING_VALUE)); // Small padding in the navigation Bar

        final VBox root = new VBox();
        root.getChildren().addAll(naviBar, webView, bottomTitle);
        VBox.setVgrow(webView, Priority.ALWAYS);

        webEngine.locationProperty().addListener((observable, oldValue, newValue) ->
                urlBox.setText(newValue));

        // If the Worker.State is in lower State than SUCCEEDED (i.e. in READY, SCHEDULED or RUNNING State),
        // then the goStopButton should be in 'Stop' configuration
        // else the goStopButton should be in 'Go' configuration
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.compareTo(Worker.State.SUCCEEDED) < 0) {
                bottomTitle.setVisible(true);
                goStopButton.setText(stopButtonUnicodeSymbol);
                goStopButton.setOnAction(e -> webEngine.getLoadWorker().cancel());
            } else {
                bottomTitle.setVisible(false);
                goStopButton.setText(goButtonUnicodeSymbol);
                goStopButton.setOnAction(e -> webEngine.load(urlBox.getText()));
            }
        });

        webEngine.getHistory().currentIndexProperty().addListener((observable, oldValue, newValue) -> {
            int length = webEngine.getHistory().getEntries().size();

            backButton.setDisable((int)newValue == 0);
            forwardButton.setDisable((int)newValue >= length - 1);
        });

        webEngine.load(initialURL);

        Scene scene = new Scene(root);
        stage.setScene(scene);

//-        SimpleStringProperty titleProp = new SimpleStringProperty("HelloWebView: ");
        SimpleStringProperty titleProp = new SimpleStringProperty("HelloWebView" +
                " (" + System.getProperty("java.version") + ") : ");
        stage.titleProperty().bind(titleProp.concat(urlBox.textProperty()));
        stage.show();
    }
 
Example 17
Source File: FxWebViewExample1.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
@Override
public void start(final Stage stage)
{
	// Create the WebView
	WebView webView = new WebView();

	// Create the WebEngine
	final WebEngine webEngine = webView.getEngine();

	// LOad the Start-Page
	webEngine.load("http://www.oracle.com");

	// Update the stage title when a new web page title is available
	webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>()
	{
           public void changed(ObservableValue<? extends State> ov, State oldState, State newState)
           {
               if (newState == State.SUCCEEDED)
               {
                   //stage.setTitle(webEngine.getLocation());
               	stage.setTitle(webEngine.getTitle());
               }
           }
       });

	// Create the VBox
	VBox root = new VBox();
	// Add the WebView to the VBox
	root.getChildren().add(webView);

	// Set the Style-properties of the VBox
	root.setStyle("-fx-padding: 10;" +
			"-fx-border-style: solid inside;" +
			"-fx-border-width: 2;" +
			"-fx-border-insets: 5;" +
			"-fx-border-radius: 5;" +
			"-fx-border-color: blue;");

	// Create the Scene
	Scene scene = new Scene(root);
	// Add  the Scene to the Stage
	stage.setScene(scene);
	// Display the Stage
	stage.show();
}
 
Example 18
Source File: WebBrowser.java    From yfiton with Apache License 2.0 4 votes vote down vote up
@Override
public void start(final Stage stage) throws Exception {
    // required to allow CORS
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

    BorderPane borderPane = new BorderPane();

    WebView browser = new WebView();
    WebEngine webEngine = browser.getEngine();
    webEngine.setUserAgent("Yfiton");

    Map<String, String> parameters = getParameters().getNamed();
    borderPane.setCenter(browser);
    webEngine.documentProperty().addListener((prop, oldDoc, newDoc) -> {
        String debugMode = parameters.get("debug");
        if (debugMode != null && debugMode.equalsIgnoreCase("true")) {
            enableFirebug(webEngine);
        }
    });
    webEngine.load(parameters.get("authorization-url"));

    Class<?> listenerClass = Class.forName(parameters.get("webengine-listener-class"));

    WebEngineListener listener =
            (WebEngineListener) listenerClass.getConstructor(
                    WebEngine.class, String.class, String.class).newInstance(
                    webEngine, parameters.get("authorization-file"), parameters.get("authorization-code-parameter-name"));

    webEngine.getLoadWorker().stateProperty().addListener(listener);

    stage.setTitle("Yfiton");

    Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();

    scene =
            new Scene(
                    borderPane,
                    primaryScreenBounds.getWidth() * 0.55,
                    primaryScreenBounds.getHeight() * 0.65);

    stage.setScene(scene);
    stage.getIcons().add(new Image(this.getClass().getResourceAsStream("/yfiton-icon.png")));
    stage.show();
    stage.setOnCloseRequest(event -> System.exit(EXIT_CODE_ON_CLOSE));
}
 
Example 19
Source File: HelpController.java    From CPUSim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Initializes the WebView pane, where
 * the help HTML pages are rendered.
 */
public void initializeWebView() {
    WebEngine webEngine = webView.getEngine();
    //webView.setZoom(javafx.stage.Screen.getPrimary().getDpi() / 96);

    webEngine.getLoadWorker().stateProperty().addListener(
            (arg0, oldState, newState) -> {
                if (newState == State.SUCCEEDED) {
                    WebEngine webEngine1 = webView.getEngine();
                    //This next two lines are a work around
                    //Due to webEngine.load() problems.
                    searchController.setDocumentCopy(webEngine1.getDocument());
                    //loads tags on change. Somewhat of a hack for handling switching
                    //between files when searching is active. Highlights words
                    //immediately when displaying a new file in the web view
                    searchController.addHighlightTagsToBody(webEngine1
                            .getDocument());
                    String s = webEngine1.getLocation();
                    int i = webEngine1.getLocation().indexOf(pref);
                    String afterPref = s.substring(i);
                    if (afterPref.contains("#")) {
                        afterPref = afterPref.substring(0, afterPref.indexOf
                                ("#"));
                    }
                    String newItemsName = urls.get(afterPref);

                    TreeItem<String> ti = getItemFromString(newItemsName,
                            treeView.getRoot());
                    if (!previousItem.getValue().equals(ti.getValue())) {
                        msm.select(ti);
                    }
                    previousItem = ti;
                }
            });

    URL url = getClass().getResource("/html/help/generalHelp/introduction.html");
    if (startingPage != null) {
        url = getClass().getResource(urls.get(startingPage));
    }
    webEngine.load(url.toExternalForm() + appendString);
}
 
Example 20
Source File: WebViewEventDispatcher.java    From oim-fx with MIT License 4 votes vote down vote up
public WebViewPane() {
	VBox.setVgrow(this, Priority.ALWAYS);
	setMaxWidth(Double.MAX_VALUE);
	setMaxHeight(Double.MAX_VALUE);

	TextField locationField = new TextField("http://www.baidu.com");
	Button goButton = new Button("Go");

	WebEngine webEngine = webView.getEngine();
	page = Accessor.getPageFor(webEngine);
	page.setJavaScriptEnabled(true);

	webView.setMinSize(500, 400);
	webView.setPrefSize(500, 400);

	webEngine.load("http://www.baidu.com");

	page.setEditable(true);

	// EventDispatcher eventDispatcher=new EventDispatcher() {
	//
	// @Override
	// public Event dispatchEvent(Event event, EventDispatchChain tail)
	// {
	// //tail.dispatchEvent(event);
	// if(event.getEventType()==MouseEvent.ANY) {
	//
	// }
	// return event;
	// }
	//
	// };
	registerEventHandlers();
	

	webView.setEventDispatcher(internalEventDispatcher);
	
	System.out.println(webView.getEventDispatcher());
	// webView.addEventHandler(eventType, eventHandler);
	// webView.buildEventDispatchChain(tail)

	EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {
		@Override
		public void handle(ActionEvent event) {
			webEngine.load(locationField.getText().startsWith("http://") ? locationField.getText() : "http://" + locationField.getText());
		}
	};

	goButton.setDefaultButton(true);
	goButton.setOnAction(goAction);

	locationField.setMaxHeight(Double.MAX_VALUE);
	locationField.setOnAction(goAction);

	webEngine.locationProperty().addListener(new ChangeListener<String>() {
		@Override
		public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
			locationField.setText(newValue);
		}
	});

	GridPane grid = new GridPane();
	grid.setVgap(5);
	grid.setHgap(5);
	GridPane.setConstraints(locationField, 0, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.SOMETIMES);
	GridPane.setConstraints(goButton, 1, 0);
	GridPane.setConstraints(webView, 0, 1, 2, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
	grid.getColumnConstraints().addAll(
			new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true),
			new ColumnConstraints(40, 40, 40, Priority.NEVER, HPos.CENTER, true));
	grid.getChildren().addAll(locationField, goButton, webView);
	getChildren().add(grid);
}