getting corresponding filename of image once button pressed

后端 未结 4 1635
南笙
南笙 2021-01-28 19:20

A Set of imagefiles are added to an arraylist(filelist2) of type File.Then an imageview and a button are affffded to a vbox,such vboxes are added to a grids of a gripane using a

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 19:49

    I've created a DataButton which can hold some typed data (unlike userData which has the type Object). You can specify a Renderer to render the data on the button or to render an alternative text, eg. in your case: "Download".

    Eg. you could use something like this:

    List pathlist2 = new ArrayList<>();
    ...
    // provide language specific text for "Download"
    ResourceBundle myResourceBundle = ...;
    ...
    DownloadRenderer downloadRenderer = new DownloadRenderer(myResourceBundle);
    ...
    // the dafault renderer would set the text property to path.toString()
    DataButton downloadbtn = new DataButton<>(downloadRenderer);
    downloadbtn.setData(pathlist2.get(index));
    downloadbtn.setOnAction((actionEvent) -> {
                Path path = downloadbtn.getData();
                ...   
         }); 
    
    ...
    
    private static class DownloadRenderer extends AbstractDataRenderer {
    
        private final ResourceBundle myResourceBundle;
    
        public DownloadRenderer(final ResourceBundle myResourceBundle) {
            this.myResourceBundle = myResourceBundle;
        }
    
        @Override
        public String getText(Object item) {
            return myResourceBundle.getString("downloadbtn.text");
        }
    } 
    
    
    

    As you can see, you can work directly with Path objects (which should be preferred to the legacy File objects). You don't have to cast or convert the data.

    Note: you could also omit the DownloadRenderer and set the text property directly:

    downloadbtn.setData(pathlist2.get(index));
    downloadbtn.setText(myResourceBundle.getString("downloadbtn.text"));
    

    But then you have to make sure to call setText always after setData.

    The library is Open Source and is available from Maven Central:

    
        org.drombler.commons
        drombler-commons-fx-core
        0.4
    
    

    提交回复
    热议问题