我想這是一件非常簡單的事情,但我無法追上它。 我想要的只是通過ImageView鏈接到fxml來顯示圖像。 這裏是我的代碼:如何使用javafx和fxml中的ImageView組件顯示圖像?
package application;
import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
public class Main extends Application
{
@FXML
private ImageView imageView;
@Override
public void start(Stage primaryStage)
{
try
{
AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("Hello World");
File file = new File("src/Box13.jpg");
Image image = new Image(file.toURI().toString());
imageView = new ImageView(image);
//root.getChildren().add(imageView);
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 java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="316.0" prefWidth="321.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.SampleController">
<children>
<ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" layoutX="61.0" layoutY="83.0" pickOnBounds="true" preserveRatio="true" >
</ImageView>
</children>
</AnchorPane>
應該有與文件鏈接,因爲它工作得很好,當我包括outcommented線沒有問題。這只是它在java中完成的方式,但是我想在這裏使用fxml,因爲我對所有其他組件使用fxml,但它不適用於ImageView,我不知道爲什麼。我也嘗試創建一個新的控制器類,並將ImageView鏈接到那裏,但這兩者都不起作用。誰能幫我?
感謝