簡體   English   中英

無法使用Netbeans IDE在JavaFX中加載圖像

[英]Can't load image in JavaFX using Netbeans IDE

這是我的代碼:

package week7;

import javafx.scene.*;
import javafx.stage.*;
import javafx.application.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.scene.image.*;

/**
 * This application demonstrates a VBox.
 */
public class VBoxExample extends Application {
public static void main(String[] args) { launch(args); }

private Label usernameLbl;
private TextField usernameTf;
private PasswordField passwordPf;
private Button loginBtn;
private ImageView imageView;

@Override
public void start(Stage stage) throws Exception {
    // Create the leaves
    usernameLbl = new Label("Username:");
    usernameTf = new TextField();
    passwordPf = new PasswordField();
    loginBtn = new Button("Login");
    imageView = new ImageView("file: flower.png");

    // Create a branch
    VBox vBox = new VBox(10);
    vBox.getChildren().addAll(usernameLbl, usernameTf, passwordPf, loginBtn, imageView);

    // Set the scene, show the stage
    stage.setScene(new Scene(vBox));
    stage.setTitle("VBox example");
    stage.show();
}
}

我嘗試使用以下代碼在VBox窗口下放置圖片:

imageView = new ImageView("file: flower.png");

該程序可以運行,但是沒有圖像顯示。 我在FXDemo1(項目)-week7(程序包)-VBoxExample(類)中創建我的項目。 而且我已經嘗試過將圖像文件放入week7包中或將其添加到build文件夾中。 我什至嘗試在/ src下創建一個名為resources的文件夾,但是它們都不起作用。

並且使用file:flower.png是程序運行的唯一方法,我也嘗試使用/flower.png或/resources/flower.png,但是它們會導致錯誤。

請告訴我們如何在Netbeans上加載映像。 謝謝!

ImageView構造函數的參數應該是URL字符串。 代替擺弄字符串,您應該只創建一個這樣的File並從中獲取URL。

imageView = new ImageView(new File("flower.png").toURI().toURL().toExternalForm());

假定文件位於執行程序的工作目錄中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM