[英]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.