javajframerefreshdefaulttablemodel

Refresh JFrame contents DefaultTableModel


I'm trying to figure out how to make a table window update once the model has changed using an example from another site. Everything works but I can't figure how to refresh the window once the table model has changed.

EDIT: I used the suggestion from Bell and re-arranged some things so that the constructor calls my getmodel3 method to populate the table. I thought I could use the setmodel method to change the model and update the table but it isn't working as I thought. Here's what I thought would, but doesn't happen:

  1. The main method creates a new instance of the table using the model passed from the getmodel3 method.
  2. After the table is constructed I call the setmodel method to load different data into a new model using the returned model from getmodel4.
  3. The instance from step 1 is updated with new model data and the new data is shown in the table.

What actually happens is, a new instance is created and uses the model returned from getmodel3, then the setmodel method runs and updates the model variable from a different set of data, but the table doesn't show the change.

    public class myTable extends JFrame
    {

    public volatile DefaultTableModel model = (DefaultTableModel) myTable.getmodel3();

    public void setmodel(DefaultTableModel newModel) 
    {
        this.model = newModel;
    }

    public myTable()
    {
        JTable table = new JTable( model );
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        myTable frame = new myTable();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
        frame.setmodel(getmodel4());
    }   

Here is getmodel3 which is identical to getmodel4 except they point to different database files for different data.

    public static DefaultTableModel getmodel3(){
    Vector<Object> columnNames = new Vector<Object>();
    Vector<Object> data = new Vector<Object>();

    try
    {
        //  Connect to an Access Database

        String url = "jdbc:sqlite:c:\\sqlite3\\test.db";
        Connection conn = DriverManager.getConnection(url);

        //  Read data from a table

        String sql = "Select * from Tasks";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery( sql );
        ResultSetMetaData md = rs.getMetaData();
        int columns = md.getColumnCount();

        //  Get column names

        for (int i = 1; i <= columns; i++)
        {
            columnNames.addElement( md.getColumnName(i) );
        }

        //  Get row data

        while (rs.next())
        {
            Vector<Object> row = new Vector<Object>(columns);

            for (int i = 1; i <= columns; i++)
            {
                row.addElement( rs.getObject(i) );
            }

            data.addElement( row );
        }

        rs.close();
        stmt.close();
        conn.close();
    }
    catch(Exception e)
    {
        System.out.println( e );
    }

    //  Create table with database data

    DefaultTableModel model = new DefaultTableModel(data, columnNames)
    {
        @Override
        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }
            }

            return Object.class;
        }
    };
System.out.println("got model");

return model;

}


Solution

  • Well, with some of your help I finally figured it out. setModel wasn't working because 1, it wasn't accessible from the scope of the method where I tried to use it, and 2 I tried to make my own setter setmodel but I had no idea what I was doing :).

    In the end, I initialized in an easier to reach place so I didn't mess with objects in other methods. Here is the working result that loads a table when main is called and later I can call the update method to reload it. Thanks for the help folks.

    public class able extends JFrame
    {
    
    //initialize here for easy access.  getmodel3() is the model getter method and 
    //returns the defaultTableModel object
    
    private static able frame =  new able();
    private static JTable table = new JTable( getmodel3() );
    
    //Start all main stuff here using the previously initialized objects.
    
    public static void main(String[] args)
    {
        JScrollPane scrollPane = new JScrollPane( table );
        frame.getContentPane().add( scrollPane );
        JPanel buttonPanel = new JPanel();
        frame.getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    
    }   
    
    public static void update()
    {
       table.setModel(getmodel3());
    }
    
    //This method makes the table model from sql result set and returns it.    
    //(found online somewhere thanks to whoever wrote it)
    
    public static DefaultTableModel getmodel3(){
        Vector<Object> columnNames = new Vector<Object>();
        Vector<Object> data = new Vector<Object>();
    
        try
        {
            //  Connect to an Access Database
    
            String url = "jdbc:sqlite:c:\\sqlite3\\test.db";
            Connection conn = DriverManager.getConnection(url);
    
            //  Read data from a table
    
            String sql = "Select * from Tasks";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
    
            //  Get column names
    
            for (int i = 1; i <= columns; i++)
            {
                columnNames.addElement( md.getColumnName(i) );
            }
    
            //  Get row data
    
            while (rs.next())
            {
                Vector<Object> row = new Vector<Object>(columns);
    
                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }
    
                data.addElement( row );
            }
    
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(Exception e)
        {
            System.out.println( e );
        }
    
        //  Create table with database data
    
        DefaultTableModel model3 = new DefaultTableModel(data, columnNames)
        {
            @Override
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);
    
                    if (o != null)
                    {
                        return o.getClass();
                    }
                }
    
                return Object.class;
            }
        };
    System.out.println("got model");
    
    return model3;
     }
    
    public static DefaultTableModel getmodel4(){
        Vector<Object> columnNames = new Vector<Object>();
        Vector<Object> data = new Vector<Object>();
    
        try
        {
            //  Connect to an Access Database
    
            String url = "jdbc:sqlite:c:\\sqlite3\\test2.db";
            Connection conn = DriverManager.getConnection(url);
    
            //  Read data from a table
    
            String sql = "Select * from Tasks";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery( sql );
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
    
            //  Get column names
    
            for (int i = 1; i <= columns; i++)
            {
                columnNames.addElement( md.getColumnName(i) );
            }
    
            //  Get row data
    
            while (rs.next())
            {
                Vector<Object> row = new Vector<Object>(columns);
    
                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }
    
                data.addElement( row );
            }
    
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(Exception e)
        {
            System.out.println( e );
        }
    
        //  Create table with database data
    
        DefaultTableModel model3 = new DefaultTableModel(data, columnNames)
        {
            @Override
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);
    
                    if (o != null)
                    {
                        return o.getClass();
                    }
                }
    
                return Object.class;
            }
        };
    System.out.println("got model");
    
    return model3;
     }
    
    
    }