使用JavaFX,我正在寻找一种打开本地HTML自述文件的方法。我知道它必须太简单,因为我无法找到任何东西。 “帮助”链接位于工具栏中的MenuItem下。
答案 0 :(得分:2)
我写了一个最小的应用来做你需要的。 主要课程是
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = FXMLLoader.load(getClass().getResource("/res/MenuWithHtmlReader.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.web.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.45" fx:controller="application.MainController">
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" onAction="#onLoadHelpFile" text="Open Readme file" />
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<WebView fx:id="webView" prefWidth="500.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
控制器是:
package application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
public class MainController {
@FXML
WebView webView;
@FXML
public void onLoadHelpFile(ActionEvent event) {
System.out.println("onLoadHelpFile clicked" + webView);
WebEngine webEngine = webView.getEngine();
webEngine.load(getClass().getResource("/res/readme.html").toExternalForm());
}
}
帮助文件readme.html是
<html>
<body>
<p>Hello, this is your local friendly help file. Do as I say and you will be totally safe.</p>
<p>No pianos will plummet down onto your head.</p>
<p>Probably.</p>
</body>
</html>
我将fxml和html文件放在res文件夹中。 我希望有所帮助。