Javafx 如何在按钮中添加图像?

Javafx 如何在按钮中添加图像?,javafx,Javafx,我正在尝试在重置按钮中添加图像(icon.jpg)。但它没有加载到按钮上。我使用了下面写的代码。但它不起作用 public StatusBar(){ statusBarGp = new GridPane(); File imagefile=new File("file:///C:/Users/Avi/Desktop/icon.jpg"); Image icon_image=new Image(imagefile.toURI().toString()); res

我正在尝试在重置按钮中添加图像(icon.jpg)。但它没有加载到按钮上。我使用了下面写的代码。但它不起作用

public StatusBar(){
    statusBarGp = new GridPane();

    File imagefile=new File("file:///C:/Users/Avi/Desktop/icon.jpg");
    Image icon_image=new Image(imagefile.toURI().toString());

    resetButton = new Button("",new ImageView(icon_image));

    whitePlayerAlert = new Label("");
    blackPlayerAlert = new Label("");
    whitePlayerTimer = new Label("");
    blackPlayerTimer = new Label("");
    Alert=new Label("");
    Alert1=new Label("");
    winner = new Label("");
    resetButton.setMaxSize(500.0, 200.0);

    resetButton.setStyle("-fx-background-radius: 10, 10, 10, 10; ");

    //statusBarGp.setGridLinesVisible(true);

    statusBarGp.setSnapToPixel(false);
    statusBarGp.setEffect(new DropShadow());


    getChildren().add(statusBarGp);
}

首先,你让这个过程变得比需要的复杂得多。
ImageView
构造函数接受参数的
URL
,您可以将图像路径直接传递给它:

resetButton = new Button(null, new ImageView("file:///C:/Users/Avi/Desktop/icon.jpg"));

如果这仍然导致一个空的
按钮
,请确认图像存在于您输入的位置。

首先,您使过程比需要的复杂得多。
ImageView
构造函数接受参数的
URL
,您可以将图像路径直接传递给它:

resetButton = new Button(null, new ImageView("file:///C:/Users/Avi/Desktop/icon.jpg"));

如果这仍然导致一个空的
按钮
,请确认图像存在于您输入的位置。

当图像不工作时到底发生了什么?它什么也不显示。只显示一个带有空文本的按钮。Afaik
文件
不接受URL,但接受文件路径。文件路径中当然不允许使用该协议,某些内容也可能有所不同。例如,在URL中,空格需要编码为
%20
。(这里的情况似乎不是这样。)当它不工作时到底发生了什么?它什么也不显示。只是一个带有空文本的按钮。Afaik
File
不接受URL,而是一个文件路径。文件路径中当然不允许使用该协议,某些内容也可能有所不同。例如,在URL中,空格需要编码为
%20
。(但这里的情况似乎并非如此。)