繁体   English   中英

在JavaFX中使用用户选择的图像创建按钮

[英]Creating a button with user-selected image in JavaFX

我正在创建一个Java应用程序,该应用程序允许用户单击一个按钮以打开文件选择器,并在选择图像后创建一个按钮,其中包含该图像和来自文本字段的文本。 它没有图像就可以工作,但是我不知道如何为我的一生将图像添加到按钮中。

上下文: btns是Buttons的GridPane, lastTopIn是一个整数,用于跟踪GridPane的最后使用的列。 单击该按钮后,该按钮将自行删除。

FileChooser fc = new FileChooser()
fc.setTitle("Choose Image for Button");
File file = fc.showOpenDialog(null);
lastTopIn++;
Button thebutton = new Button((String) tf.getText(), new ImageView(new Image(getClass().getResourceAsStream("file://"+file.getAbsolutePath()))));
    thebutton.setOnMouseClicked(new EventHandler<Event>() {
        @Override
        public void handle(Event event) {
            btns.getChildren().remove(thebutton);                           
        }
    });
btns.add(thebutton, lastTopIn,1);

在此先感谢您的帮助。

要显示文件系统上文件的图像,请将文件转换为URI,而不是尝试将其作为资源加载:

Button thebutton = new Button(tf.getText(), 
    new ImageView(new Image(file.toURI().toString())));

file.ToURI()将创建正确的URI方案,并正确转义文件名中合法但URI中非法的任何字符(如空格)。

请注意,作为一种快捷方式,您可以将URI直接传递给ImageView构造函数,它将为您创建图像:

Button thebutton = new Button(tf.getText(), new ImageView(file.toURI().toString()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM