javaswingjtabledefaulttablemodel

JTable populated but not shown. Using DefaultTableModel


I can't understand why my JTable does not update.

Below is my code:

package it.franpic.chat.client.prestazioni.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.List;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import it.franpic.chat.client.prestazioni.model.RecordBean;

public class FinestraPrincipale {

    private JFrame frame;
    private JTable tabellaDati;
    private JScrollPane scrollPaneTabella;
    private JSplitPane splitPaneContenuti;

    /**
     * Launch the application.
     */
    public void avvia() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FinestraPrincipale window = new FinestraPrincipale();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public FinestraPrincipale() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel pnlOpzioni = new JPanel();
        frame.getContentPane().add(pnlOpzioni, BorderLayout.NORTH);
        pnlOpzioni.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Opzioni", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
        pnlOpzioni.setLayout(new BorderLayout(0, 0));

        JCheckBox chckbxAggiornaAutomaticamente = new JCheckBox("Aggiorna Automaticamente");
        chckbxAggiornaAutomaticamente.setEnabled(false);
        pnlOpzioni.add(chckbxAggiornaAutomaticamente);
        chckbxAggiornaAutomaticamente.setVerticalAlignment(SwingConstants.TOP);

        splitPaneContenuti = new JSplitPane();
        splitPaneContenuti.setOneTouchExpandable(true);
        splitPaneContenuti.setOrientation(JSplitPane.VERTICAL_SPLIT);
        frame.getContentPane().add(splitPaneContenuti, BorderLayout.CENTER);

        JScrollPane scrollPaneGrafico = new JScrollPane();
        splitPaneContenuti.setLeftComponent(scrollPaneGrafico);

        scrollPaneTabella = new JScrollPane();
        splitPaneContenuti.setRightComponent(scrollPaneTabella);

        tabellaDati = new JTable();
        tabellaDati.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "ISTANTE", "GESTITE", "DISTRIBUITE", "PIANIFICATO", "SOSTENIBILE", "LOGGATI", "LOGGATI_PIANIFICATO"
            }
        ) {
            Class[] columnTypes = new Class[] {
                String.class, Integer.class, Integer.class, Integer.class, Integer.class, Integer.class, Integer.class
            };
            public Class getColumnClass(int columnIndex) {
                return columnTypes[columnIndex];
            }
        });
        tabellaDati.getColumnModel().getColumn(3).setPreferredWidth(76);
        tabellaDati.getColumnModel().getColumn(6).setPreferredWidth(127);
        tabellaDati.setColumnSelectionAllowed(true);
        tabellaDati.setCellSelectionEnabled(true);
        scrollPaneTabella.setViewportView(tabellaDati);
    }

    public void aggiornaTabella(List<RecordBean> lista) {
        DefaultTableModel model = (DefaultTableModel) tabellaDati.getModel();
        model.setRowCount(0);
        System.out.println("tabellaDati.getRowCount() = " + tabellaDati.getRowCount());

        for (RecordBean record : lista) {
            model.addRow(new Object[]{record.getMomento(), record.getGestite(), record.getDistribuite(), record.getSostenibile(), record.getPianificato(), record.getLoggati(), record.getLoggatiPianificato()});
        }

        System.out.println("tabellaDati.getRowCount() = " + tabellaDati.getRowCount());
    }   

}

This is the code of main class that call those methods:

package it.franpic.chat.client.prestazioni.control;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import it.franpic.chat.client.prestazioni.model.RecordBean;
import it.franpic.chat.client.prestazioni.view.FinestraPrincipale;

public class Client {
    public static void main(String[] args) {
        FinestraPrincipale finestraPrincipale = new FinestraPrincipale();
        GestoreDb gestoreDb = new GestoreDb();


        String adessoFormatoMySql = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));

        List<RecordBean> lista = gestoreDb.getRecordsDaDate("2019-01-26 18:00:00", adessoFormatoMySql);

        finestraPrincipale.avvia();
        finestraPrincipale.aggiornaTabella(lista);
    }
}

From the other discussions and documentation, I think my code is fine but evidently it is not.

The table is correctly showed when constructed but is not updated by the aggiornaTabella(List<RecordBean> lista) method. I can't figure why.

I've tried, in aggiornaTabella(List<RecordBean> lista), after the addRow cycle:

From the 2 println in aggiornaTabella(List<RecordBean> lista) method I can see that the rows of the JTable are populated but they are not shown.


Solution

  • This...

    public class Client {
        public static void main(String[] args) {
            FinestraPrincipale finestraPrincipale = new FinestraPrincipale();
            GestoreDb gestoreDb = new GestoreDb();
    
    
            String adessoFormatoMySql = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    
            List<RecordBean> lista = gestoreDb.getRecordsDaDate("2019-01-26 18:00:00", adessoFormatoMySql);
    
            finestraPrincipale.avvia();
            finestraPrincipale.aggiornaTabella(lista);
        }
    }
    

    explains a lot.

    First, you create an instance of FinestraPrincipale, load some data and call finestraPrincipale.avvia, but avvia is creating a new instance of FinestraPrincipale

    public void avvia() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    // Hello new instance...
                    FinestraPrincipale window = new FinestraPrincipale();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    which is been displayed on the screen, it has nothing to do with the instance you original created (and are updating)

    avvia should not be creating a new instance, it should simply be using itself and the state which was previous initialised when it was constructed...

    public void avvia() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    That alone should go a long way to fixing your issue