我一直在使用桌面应用程序,我需要使用JavaFX。我在eclipse上的JavaFX项目中创建了一个fxml
文件。我在场景构建器中构建场景。当我尝试运行主Java文件时,使用fxml
文件上的场景构建器所做的更改不会反映在主窗口上。并且屏幕显示为空白。这是我的代码。
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
AnchorPane root = new AnchorPane();
Scene scene = new Scene(root,400,400,Color.BLACK);
scene.getStylesheets().add(getClass().getResource("/application/sample.fxml").getPath());
primaryStage.setTitle("FXML Welcome");
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
这是我的sample.fxml
文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?scenebuilder-background-color 0x00ffa3ff?>
<AnchorPane prefHeight="379.0" prefWidth="549.0001220703125" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">
<children>
<Button layoutX="219.0" layoutY="156.0" mnemonicParsing="false" text="hello" />
</children>
</AnchorPane>
我得到的错误是:
WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "/F:/eclipse_progs/examplefx/bin/application/sample.fxml" not found.
但指定错误中的位置包含它所引用的文件。任何人都可以解释错误的原因。是代码还是插件问题?
答案 0 :(得分:4)
尝试此启动方法,并将目录application/<NAME>.fxml
放在Main.class
所在的同一目录中
fxml文件加载了静态FXMLLoader.load()
方法
使用getStylesheets.add(...)
,您可以将.css文件添加到场景中。
@Override
public void start(Stage primaryStage) throws IOException {
Parent parent = FXMLLoader.load(getClass().getResource("application/demo.fxml"));
Scene scene = new Scene(parent);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
答案 1 :(得分:3)
在JavaFX中,如果要加载fxml文件,请使用FXMLLoader,
FXMLLoader.load(getClass().getResource("application/sample.fxml"));
将样式表加载为。
scene.getStlyeShees().add(getClass().getResource("application/sample.css").toExternalForm);
在您的代码中,您将fxml文件添加到错误的场景的样式表列表中。尝试使用如上所述的FXMLLoader来加载你的fxml文件。
参考文档:http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm