我是JavaFX的初学者。
我在JavaFX Scene Builder中制作了我的布局。在那里我留下了一个WebView但我无法想象如何给它一个URL。
在一个单独的类中,我已经准备好了WebView
public class GoogleApp extends Application {
private Scene scene;
MyBrowser myBrowser;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Railway Scenario Development");
myBrowser = new MyBrowser();
scene = new Scene(myBrowser, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
class MyBrowser extends Region{
HBox toolbar;
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
public MyBrowser(){
final URL urlGoogleMaps = getClass().getResource("demo.html");
webEngine.load(urlGoogleMaps.toExternalForm());
getChildren().add(webView);
}
}
}
但是我需要将它嵌入到我在Scene Builder中创建的应用程序中。在Scene Builder中有一个WebView面板,我希望该面板看起来像我上面提到的代码。
我的应用程序代码使用fxml文件作为其“场景”(如下所示)。
public class Railway extends Application {
private Scene scene;
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
stage.setTitle("Railway Scenario Development");
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我想我要在FXMLDocumentController文件中做一些事情。但是如何以及如何。请指导。
现在它的工作完美...试试这个
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
public class FXMLDocumentController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private StackPane root;
@FXML
void initialize() {
assert root != null : "fx:id=\"root\" was not injected: check your FXML file 'FXMLDocument.fxml'.";
WebView view = new WebView();
WebEngine engine = view.getEngine();
engine.load("http://www.google.com/");
root.getChildren().add(view);
}
}
我找到了第一个版本的方法。
也许其他人可以试试这个:http://java-buddy.blogspot.de/2012/05/embed-webview-in-fxml-to-load.html。
它对我有用。
这是一个示例FXML文件。
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafxml_web.*?><!--- Important Use your own Package instead of "javafxml_web.*" --->
<AnchorPane id="AnchorPane" prefHeight="500" prefWidth="660" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxml_web.Sample">
<children>
<MyBrowser id="mybrowser" layoutX="10" layoutY="10" prefHeight="460" prefWidth="620" fx:id="mybrowser" />
</children>
</AnchorPane>
在你的Controllerclass中你必须使用:
@FXML
private MyBrowser mybrowser;
这应该可以解决您的问题。