getting corresponding filename of image once butto

2020-05-08 22:40发布

A Set of imagefiles are added to an arraylist(filelist2) of type File.Then an imageview and a button are addded to a vbox,such vboxes are added to a grids of a gripane using a for loop.( number of iterations is equal to size of the filelist2)Once a button is pressed I need to get the corresponding filename of the image within that vbox. Say I pressed the button contained at (1,1) {i.e row no01 ,col no1} I need to get filename of image at (1,1) here's a screenshot:enter image description here

here's my code: FXMLController

 File file = new File("D:\\SERVER\\Server Content\\Apps\\icons");
            File[] filelist1 = file.listFiles();
            ArrayList<File> filelist2 = new ArrayList<>();

            for (File file1 : filelist1) {
                filelist2.add(file1);

            }
            btnar = new ArrayList<>();
            for (int i = 0; i < filelist2.size(); i++) {
                downloadbtn = new Button("Download");
                btnar.add(downloadbtn);
                final int index=i;
                downloadbtn.setId(String.valueOf(index));
                downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent arg0) {
                        try {
                            System.out.println("sssss");                             
                            downloadbtn.getId();
                            //System.out.println(filelist2.get(Integer.valueOf(downloadbtn.getId())).getName());   

                        } catch (Exception ex) {
                            Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
                        }


                    }
                });
            }

            System.out.println(filelist2.size());
            gridpane.setAlignment(Pos.CENTER);
            gridpane.setPadding(new Insets(20, 20, 20, 20));

            gridpane.setHgap(20);
            gridpane.setVgap(20);

            ColumnConstraints columnConstraints = new ColumnConstraints();
            columnConstraints.setFillWidth(true);
            columnConstraints.setHgrow(Priority.ALWAYS);
            gridpane.getColumnConstraints().add(columnConstraints);

            int imageCol = 0;
            int imageRow = 0;

            for (int i = 0; i < filelist2.size(); i++) {
                System.out.println(filelist2.get(i).getName());

                image = new Image(filelist2.get(i).toURI().toString());

                pic = new ImageView();
                pic.setFitWidth(130);
                pic.setFitHeight(130);


                pic.setImage(image);
                vb = new VBox();
                vb.getChildren().addAll(pic, (Button) btnar.get(i));

                gridpane.add(vb, imageCol, imageRow);
                GridPane.setMargin(pic, new Insets(2, 2, 2, 2));
                imageCol++;

                // To check if all the 3 images of a row are completed
                if (imageCol > 2) {
                    // Reset Column
                    imageCol = 0;
                    // Next Row
                    imageRow++;
                }

            }

4条回答
贼婆χ
2楼-- · 2020-05-08 23:20

Consider using a java.util.HashMap<Button, File> and calling hashMap.get(actionEvent.getSource()).getName() to get the file name.

查看更多
霸刀☆藐视天下
3楼-- · 2020-05-08 23:21

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<Path> 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<Path> downloadbtn = new DataButton<>(downloadRenderer);
downloadbtn.setData(pathlist2.get(index));
downloadbtn.setOnAction((actionEvent) -> {
            Path path = downloadbtn.getData();
            ...   
     }); 

...

private static class DownloadRenderer extends AbstractDataRenderer<Object> {

    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:

<dependency>
    <groupId>org.drombler.commons</groupId>
    <artifactId>drombler-commons-fx-core</artifactId>
    <version>0.4</version>
</dependency>
查看更多
走好不送
4楼-- · 2020-05-08 23:28

Why not simply

System.out.println(filelist2.get(index).getName());

?

(Actually, it's not really clear to me why you create filelist2 at all. Why not do

btnar = new ArrayList<>();

for (int i=0; i < filelist1.length; i++) {
        downloadbtn = new Button("Download");
        btnar.add(downloadbtn);
        final int index=i;
        downloadbtn.setId(String.valueOf(index));
        downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                try {
                    System.out.println("sssss");                             
                    System.out.println(filelist1[index].getName());   

                } catch (Exception ex) {
                    Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
                }


            }
        });
    }
查看更多
我想做一个坏孩纸
5楼-- · 2020-05-08 23:39

Use setUserData and getUserData to store and retrieve custom values in Nodes ! Set the fileName as the userdata and on click, retrieve it.

downloadbtn.setUserData(filelist2.get(index).getName());
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
     @Override
     public void handle(ActionEvent arg0) {
            System.out.println(downloadbtn.getUserData());   
     } 
查看更多
登录 后发表回答