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);
}
}
}
}