vendredi 6 septembre 2019

How to choose specific random image from folder with Jfilechoose and pass it to another method? [on hold]

I have a folder full of images, and I have to choose a random image from the folder. After I choose it I can display it in a JPanel to do some processing on it in another method. My problem is that it is always processing the first image in that folder, not chosen one. If I press next button or previous button to view images in that folder it moves with normal order from first one not the chosen random one.

This is the method to get the selected image from JFileChooser:

private static JFileChooser  imgch = new JFileChooser();

private String[] getImages() {
    File   file = imgch.getSelectedFile().getParentFile();
    String[] imagesList = file.list();        
    return imagesList;
}

And I pass this String (path) as InputStream to another method:

private void showImage(int index) throws IOException {
    String[] imagesList = getImages();
    String imageName = imagesList[index];
    File    file = imgch.getCurrentDirectory();
    path = file.getAbsolutePath().concat("/"+imageName);
    ImageIcon icon= new ImageIcon(path);
}

This is how I choose a file:

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == img1) {
        int returnVal = imgch.showOpenDialog(ObjectDetector.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                file = imgch.getSelectedFile(); 
                showImage(pos);
                BufferedImage newImage = null; 
                newImage = ImageIO.read(file);
                Image newImg = newImage.getScaledInstance(640, 480, Image.SCALE_SMOOTH);
                ImageIcon image = new ImageIcon(newImg);
                viewer.setIcon(image);
            } catch (IOException ex) {}
        } else {
            System.out.println("Process was cancelled by user.");
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire