I am working on a Java Swing project and I am trying to understand how to use JTable
.
I have a text file with a list of user information which is all separated by a comma without spaces. I am trying to get this information to be displayed in a table, however, when I run the form the table, it remains blank and never shows anything.
Here is my code:
private JTable listUsersTable;
// ...
String[] columnNames = {"USERNAME", "NAME", "SURNAME", "AGE", "SEX", "SITE"};
// Creates a table with the column names and zero rows.
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
try {
BufferedReader reader = new BufferedReader(new FileReader("userArchive.txt"));
// Reads each line in the file "userArchive.txt", separates the data, and puts them into the table.
String line = reader.readLine();
while (line != null) {
String[] lineSplit = line.split(",");
model.addRow(lineSplit);
line = reader.readLine(); // Goes to the next line in the file.
}
reader.close();
listUsersTable = new JTable(model);
} catch (FileNotFoundException e5) {
e5.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
And here is my current JTable layout & settings using intelliJ's GUI designer:
Image of my intelliJ GUI designer setup and the JTable in question.
(The JTable in the image is called verUsuariosTable
however in the code this is called listUsersTable
. This is because I am writing my code in Spanish but translating everything to ask the question).
I needed to include JScrollPane to the code. This link shows completely what is needed to work with text files and JTables. (How do I read separate parts from a txt File to show in Java GUI?).
I needed to add
listUsersTable.setPreferredScrollableViewportSize(listUsersTable.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(listUsersTable);
and then add the scrollPane to the panel I was working with using
currentPanel.add(scrollPane);