'Load CSV File into JTable

My Code:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JTable;
import java.io.*;
import java.util.*;
import java.awt.Color;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.Font;
import java.io.*;

import java.util.*;
import java.awt.Color;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.Font;
public class students extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private DefaultTableModel m;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    students frame = new students();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public students() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1280, 740);
        contentPane = new JPanel();
        contentPane.setBackground(new Color(24,24,24));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        studentTable();
        System.out.println("students();");

    }
    
    public void studentTable() {
        try {
            System.out.println("studentTable();");
            String datafile = "data.txt";
            FileReader fin = new FileReader(datafile);
            DefaultTableModel m = createTableModel(fin, null);
            
            JPanel panel = new JPanel();
            panel.setBackground(new Color(35,35,35));
            panel.setBounds(240, 163, 800, 360);
            contentPane.add(panel);
            panel.setLayout(null);
            table = new JTable(m);
            table.setBounds(0, 0, 800, 360);
            table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 12));
            table.getTableHeader().setOpaque(false);
            table.setBackground(new Color(35, 35, 35));
            table.getTableHeader().setBackground(new Color(35,35,35));
            table.setForeground(new Color(255,255,255));
            table.getTableHeader().setForeground(new Color(255,255,255));
            table.setRowHeight(25);
            table.setFocusable(false);
            table.setIntercellSpacing(new java.awt.Dimension(0, 0));
            table.setRowHeight(25);
            table.setSelectionBackground(new Color(32, 32, 32));
            table.setShowVerticalLines(false);
            table.getTableHeader().setReorderingAllowed(false);
            
            


            FileWriter out = new FileWriter("data.csv");
            defaultTableModelToStream(m, out);
            out.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void defaultTableModelToStream(DefaultTableModel dtm,
            Writer out) throws IOException {
            System.out.println("defaultTableModelToStream();");
            final String LINE_SEP = System.getProperty("line.separator");
            int numCols = dtm.getColumnCount();
            int numRows = dtm.getRowCount();

            // Write headers
            String sep = "";

            for (int i = 0; i < numCols; i++) {
                out.write(sep);
                out.write(dtm.getColumnName(i));
                sep = ",";
            }

            out.write(LINE_SEP);

            for (int r = 0; r < numRows; r++) {
                sep = "";

                for (int c = 0; c < numCols; c++) {
                    out.write(sep);
                    out.write(dtm.getValueAt(r, c).toString());
                    sep = ",";
                }

                out.write(LINE_SEP);
            }
        }
    
    public static DefaultTableModel createTableModel(Reader in,
            Vector<Object> headers) {
        System.out.println("DefaultTableModel();");

            DefaultTableModel model = null;
            Scanner s = null;

            try {
                Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
                s = new Scanner(in);

                while (s.hasNextLine()) {
                    rows.add(new Vector<Object>(Arrays.asList(s.nextLine()
                                                               .split("\\s*,\\s*",
                                    -1))));
                }

                if (headers == null) {
                    headers = rows.remove(0);
                    model = new DefaultTableModel(rows, headers);
                } else {
                    model = new DefaultTableModel(rows, headers);
                }

                return model;
            } finally {
                s.close();
            }
        }
}

Whats happening: The table doesn't load nor is it loading the 'data.txt'. The execution order is: and there are no crashes or errors showing in console. The textfile is found.

Whats supposed to happen A JTable should be on a JPanel with data pulled from a text file and loading it.

I tried to fix it by myself but nothing worked out. Maybe someone will have a solution. Thanks!



Solution 1:[1]

The short answer is, you never add the JTable to anything

The long answer is, well, a lot more complicated.

null layouts (pixel perfect layouts) are an illusion in modern UI development, to many factors go into determine and maintaining the size and relationships of components for you to waste your time reinventing what is already, easily, available to you.

Instead, take the time read and learn how to use layout managers.

Your students class is doing too much work (and is very hard to read and reason about), it should focus on doing one job and doing it well, that is, displaying the table of data. There's also no reason to extend from JFrame, you're not adding any new functionality to the class and are just making it more complex than it needs to be. Instead, start with a simple container class, like JPanel, for example...

public class StudentsPane extends JPanel {

    private JTable table;
    private DefaultTableModel m;

    public StudentsPane(TableModel model) {
        setLayout(new BorderLayout());
        setBackground(new Color(24, 24, 24));
        setBorder(new EmptyBorder(50, 50, 50, 50));

        table = new JTable(model);
        table.setFillsViewportHeight(true);
        table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 12));
        table.getTableHeader().setOpaque(false);
        table.setBackground(new Color(35, 35, 35));
        table.getTableHeader().setBackground(new Color(35, 35, 35));
        table.setForeground(new Color(255, 255, 255));
        table.getTableHeader().setForeground(new Color(255, 255, 255));
        table.setFocusable(false);
        table.setIntercellSpacing(new java.awt.Dimension(0, 0));
        table.setRowHeight(25);
        table.setSelectionBackground(new Color(32, 32, 32));
        table.setShowVerticalLines(false);
        table.getTableHeader().setReorderingAllowed(false);
        add(new JScrollPane(table));
    }
}

Now, the panel doesn't care where the data comes from, only that it is responsible for displaying the supplied model.

Seperate the loading/saving of the data to it's own class (take a look at Single Responsibility Principle for the reasons why) and make sure that you are managing your resources correctly, see The try-with-resources Statement for more details on how this might be achieved, for example...

public class StudentsManager {
    public static TableModel loadFrom(File file) throws IOException {
        return loadFrom(file, null);
    }

    public static TableModel loadFrom(File file, Vector<Object> headers) throws IOException {
        try (Reader is = new FileReader(file)) {
            return loadFrom(is, headers);
        }
    }

    public static TableModel loadFrom(Reader is) {
        return loadFrom(is, null);
    }

    public static TableModel loadFrom(Reader reader, Vector<Object> headers) {
        DefaultTableModel model = null;
        Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
        Scanner s = new Scanner(reader);
        while (s.hasNextLine()) {
            rows.add(new Vector<Object>(Arrays.asList(s.nextLine().split("\\s*,\\s*"))));
        }

        if (headers == null) {
            headers = rows.remove(0);
        }
        model = new DefaultTableModel(rows, headers);
        return model;
    }

    public static void writeTo(DefaultTableModel dtm, File file) throws IOException {
        try (Writer writer = new FileWriter(file)) {
            writeTo(dtm, writer);
        }
    }

    public static void writeTo(DefaultTableModel dtm, Writer out) throws IOException {
        final String LINE_SEP = System.getProperty("line.separator");
        int numCols = dtm.getColumnCount();
        int numRows = dtm.getRowCount();

        StringJoiner joiner = new StringJoiner(",");
        for (int i = 0; i < numCols; i++) {
            joiner.add(dtm.getColumnName(i));
        }
        out.write(joiner.toString());

        out.write(LINE_SEP);

        for (int r = 0; r < numRows; r++) {
            joiner = new StringJoiner(",");
            for (int c = 0; c < numCols; c++) {
                joiner.add(dtm.getValueAt(r, c).toString());
            }
            out.write(joiner.toString());
            out.write(LINE_SEP);
        }
    }
}

And when you're ready, simply load the data and display the panel...

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            TableModel model = StudentsManager.loadFrom(new File("data.txt"));
            JFrame frame = new JFrame();
            frame.add(new StudentsPane(model));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
});

Runnable example...

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import javax.swing.JPanel;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    TableModel model = StudentsManager.loadFrom(new File("data.txt"));
                    JFrame frame = new JFrame();
                    frame.add(new StudentsPane(model));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class StudentsManager {
        public static TableModel loadFrom(File file) throws IOException {
            return loadFrom(file, null);
        }

        public static TableModel loadFrom(File file, Vector<Object> headers) throws IOException {
            try (Reader is = new FileReader(file)) {
                return loadFrom(is, headers);
            }
        }

        public static TableModel loadFrom(Reader is) {
            return loadFrom(is, null);
        }

        public static TableModel loadFrom(Reader reader, Vector<Object> headers) {
            DefaultTableModel model = null;
            Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
            Scanner s = new Scanner(reader);
            while (s.hasNextLine()) {
                rows.add(new Vector<Object>(Arrays.asList(s.nextLine().split("\\s*,\\s*"))));
            }

            if (headers == null) {
                headers = rows.remove(0);
            }
            model = new DefaultTableModel(rows, headers);
            return model;
        }

        public static void writeTo(DefaultTableModel dtm, File file) throws IOException {
            try (Writer writer = new FileWriter(file)) {
                writeTo(dtm, writer);
            }
        }

        public static void writeTo(DefaultTableModel dtm, Writer out) throws IOException {
            final String LINE_SEP = System.getProperty("line.separator");
            int numCols = dtm.getColumnCount();
            int numRows = dtm.getRowCount();

            StringJoiner joiner = new StringJoiner(",");
            for (int i = 0; i < numCols; i++) {
                joiner.add(dtm.getColumnName(i));
            }
            out.write(joiner.toString());

            out.write(LINE_SEP);

            for (int r = 0; r < numRows; r++) {
                joiner = new StringJoiner(",");
                for (int c = 0; c < numCols; c++) {
                    joiner.add(dtm.getValueAt(r, c).toString());
                }
                out.write(joiner.toString());
                out.write(LINE_SEP);
            }
        }
    }

    public class StudentsPane extends JPanel {

        private JTable table;
        private DefaultTableModel m;

        public StudentsPane(TableModel model) {
            setLayout(new BorderLayout());
            setBackground(new Color(24, 24, 24));
            setBorder(new EmptyBorder(50, 50, 50, 50));

            table = new JTable(model);
            table.setFillsViewportHeight(true);
            table.getTableHeader().setFont(new Font("Arial", Font.BOLD, 12));
            table.getTableHeader().setOpaque(false);
            table.setBackground(new Color(35, 35, 35));
            table.getTableHeader().setBackground(new Color(35, 35, 35));
            table.setForeground(new Color(255, 255, 255));
            table.getTableHeader().setForeground(new Color(255, 255, 255));
            table.setFocusable(false);
            table.setIntercellSpacing(new java.awt.Dimension(0, 0));
            table.setRowHeight(25);
            table.setSelectionBackground(new Color(32, 32, 32));
            table.setShowVerticalLines(false);
            table.getTableHeader().setReorderingAllowed(false);
            add(new JScrollPane(table));
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MadProgrammer