繁体   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