gpt4 book ai didi

Java FXML 从绝对路径加载(动态)

转载 作者:行者123 更新时间:2023-12-02 09:19:58 25 4
gpt4 key购买 nike

我想从绝对路径或 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 ...
}

enter image description here

最佳答案

应该很简单:

Parent root = FXMLLoader.load(Paths.get(fxmlpath).toUri().toURL());

FXMLLoader 将 URL 作为其参数,因此我们只需使用 NIO Paths 类来获取 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();
}
}

示例 Controller :

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>

关于Java FXML 从绝对路径加载(动态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25605499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com