我想从绝对路径或 jar 系统外部的路径加载 fxml 文件。
背景:
它将是一个简单的插件系统,在插件文件夹中查找所有 fxml 文件(后来的 jar 文件),并将其自动包含在 TabPane 中。
String fxmlpath = "C:\\plugin\\pluginfxml.fxml";
try {
Parent root = FXMLLoader.load(getClass().getResource(fxmlpath));
//Load root in Tabpane and so on ...
}
应该很简单:
Parent root = FXMLLoader.load(Paths.get(fxmlpath).toUri().toURL());
FXMLLoader 接受一个 URL 作为参数,所以我们只使用 NIOPaths类来获取 Path,然后将其转换为 URL。如果程序没有对文件位置的读取访问权限,则会出现唯一的问题。
我使用 JavaFX 教程中的示例代码充实了该示例:
测试应用:
package javafx;
import java.net.URL;
import java.nio.file.Paths;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FXMLTest extends Application {
public static void main(String[] args) {
Application.launch(FXMLTest.class, args);
}
@Override
public void start(Stage stage) throws Exception {
URL fxmlURL = Paths.get("C:\\test\\fxml_example.fxml").toUri().toURL();
Parent root = FXMLLoader.load(fxmlURL);
stage.setTitle("FXML Welcome");
Scene myScene = new Scene(root, 300, 275);
stage.setScene(myScene);
stage.show();
}
}
控制器示例:
package javafx;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
public class FXMLExampleController {
@FXML private Text actiontarget;
@FXML protected void handleSubmitButtonAction(ActionEvent event) {
actiontarget.setText("Sign in button pressed");
}
}
FXML 示例:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<GridPane fx:controller="javafx.FXMLExampleController"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"
styleClass="root">
<padding><Insets top="25" right="25" bottom="25" left="25"/></padding>
<Text id="welcome-text" text="Welcome"
GridPane.columnIndex="0" GridPane.rowIndex="0"
GridPane.columnSpan="2"/>
<Label text="User Name:"
GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<TextField
GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<Label text="Password:"
GridPane.columnIndex="0" GridPane.rowIndex="2"/>
<PasswordField fx:id="passwordField"
GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<HBox spacing="10" alignment="bottom_right"
GridPane.columnIndex="1" GridPane.rowIndex="4">
<Button text="Sign In"
onAction="#handleSubmitButtonAction"/>
</HBox>
<Text fx:id="actiontarget"
GridPane.columnIndex="1" GridPane.rowIndex="6"/>
<stylesheets>
<URL value="@Login.css" />
</stylesheets>
</GridPane>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)