I am in the very early days of learning Java and currently looking at GUIs.
I would like to be able to make a series of buttons corresponding to each file found in the folder. For example, the name of the file could appear inside the button. At this stage the buttons DON'T need to do anything !
I have managed to make separate programs which (a) Produces an array of file names found in the folder. (b) Produces a set of buttons using a for loop. However, my attempts at combining the two have been laughable. My knowledge of OO Java just doesn't cut the mustard.
Please could somebody advise me on how to proceed? Please keep it simple!
ButtonGrid.java
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridLayout;
public class ButtonGrid {
JFrame frame=new JFrame();
JButton[][] grid;
public ButtonGrid(int width, int length){
frame.setLayout(new GridLayout(width,length));
grid=new JButton[width][length];
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton("("+x+","+y+")");
frame.add(grid[x][y]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new ButtonGrid(3,3);
}
}
ListFiles.Java
import java.io.File;
public class ListFiles
{
public static void main(String[] args)
{
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}