JavaFX:使用 fxml 添加应用程序图标

JavaFX: Adding Application-Icon with fxml

我想在我的程序中添加一个应用程序图标。我试过按以下方式进行操作,但没有成功:

primaryStage.getIcons().add(new Image(Main.class.getResourceAsStream("lock.png")));
    primaryStage.getIcons().add(new Image(Controller.class.getResourceAsStream("lock.png")));
    final Parent root = FXMLLoader.load(getClass().getResource("passwordGenerator.fxml"));

primaryStage.getIcons().add(new Image("lock.png"));

我也尝试在没有 FXML 文件的情况下这样做,并且成功了。

如何在 FXML 文件中添加应用程序图标?

这里是适用于我的解决方案: 主要 class :

public class JavaFXIcons extends Application {
@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);
    stage.getIcons().add(new Image(JavaFXIcons.class.getResourceAsStream("Whosebug.jpg"))) ;
    stage.setScene(scene);
    stage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
  }
}

FXML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxicons.FXMLDocumentController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>