Question

Hi i am trying to fetch one by one item from selected directory but problem is that when i click on menu item next then all comes together from directory. i have put actionlistener on menuitem click and try to store one by one item in string variable and print on console but at a time all item loads what i will have to do ?

my code :

final JFileChooser file;
file = new JFileChooser();

file.showOpenDialog(contentPane);
        mnLoadDirectory.add(mntmSelectDir);
        File[] filesInDirectory = file.getCurrentDirectory().listFiles();
        String FileNames;
        //int i=1;

        JMenuItem mntmNextItem = new JMenuItem("Next Item");

        for (int i = 0; i < filesInDirectory.length; i++) 
        {
            if (filesInDirectory[i].isFile()) 
            {
                FileNames = filesInDirectory[i].getName();
                if (FileNames.endsWith(".jpg") || FileNames.endsWith(".JPG"))
                {
                    System.out.println(FileNames);
                }
            }
        }   



        mntmNextItem.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent arg0) 
            {           

            }
        });     
        mnLoadDirectory.add(mntmNextItem);      

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

i don't have put all code, i just put a code related to this one only.

any suggestion ???

Was it helpful?

Solution

To access filesInDirectory from inside your action listener you will need to declare it final

final File[] filesInDirectory = file.getCurrentDirectory().listFiles();

What you are doing is iterating all the files and printing out the file names it looks like you want to move your for loop into your action listener and add a break. So you'd have something like.

    mntmNextItem.addActionListener(new ActionListener()
    {
        int i = 0;

        @Override
        public void actionPerformed(ActionEvent arg0) 
        {   
            if(i == filesInDirectory.length) {
                System.out.println("You are at the end");
            }        
            else {
                for (; i < filesInDirectory.length; i++) 
                {
                    if (filesInDirectory[i].isFile()) 
                    {
                        FileNames = filesInDirectory[i].getName();
                        if (FileNames.endsWith(".jpg") || FileNames.endsWith(".JPG"))
                        {
                            System.out.println(FileNames);
                            break;
                        }
                    }
                } 
            }
        }
    });

OTHER TIPS

Read the file contents into a List or array. Maintain some kind of int value that points to the current element begin shown.

When you're ready to move to the next element, increment the int value, perform appropriate edge checks and update the display as required.

Updated with simple example

This is a basic example. It scans a specified directory into a List and maintains a int index of the current file.

When the next menu item is actioned, it simple increments the int index value and updates the display

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class NextFile {

    public static void main(String[] args) {
        new NextFile();
    }

    private FilePane filePane;

    public NextFile() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                filePane = new FilePane();
                JMenuBar mb = new JMenuBar();
                JMenu fileMenu = new JMenu("File");
                mb.add(fileMenu);
                JMenuItem mntmNextItem = new JMenuItem("Next Item");
                fileMenu.add(mntmNextItem);

                mntmNextItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        filePane.nextFile();
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setJMenuBar(mb);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(filePane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class FilePane extends JPanel {

        private JTextField path;
        private List<File> files;
        private int fileIndex = -1;

        public FilePane() {

            File parentPath = new File("/path/to/your/directory");
            File[] childFiles = parentPath.listFiles();
            files = new ArrayList<>(Arrays.asList(childFiles));

            setLayout(new GridBagLayout());
            path = new JTextField(20);
            add(path);

            nextFile();

        }

        public void nextFile() {
            if (files.size() > 0) {
                fileIndex++;
                if (fileIndex >= files.size()) {
                    fileIndex = 0;
                }
                path.setText(files.get(fileIndex).getPath());
                path.setCaretPosition(path.getText().length());
                path.moveCaretPosition(0);
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top