Updating JTable data

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Updating JTable data

Breno Jacinto Duarte da Costa
Hello guys,

    I've been using Glazed Lists for a month or so, and I must thank
and congratulate everyone in this project - it's awesome!!

    I'm posting here as I have searched google extensively, but got no
answer to my issue. I'm using a JTable within a JFrame, to display
data from a DB. When the user double clicks on the selected row,
there's a JDialog with the information of row, in form view. Then the
user may change some information and save it - thats the catch.

    Here's the bean that represents a row in my table:

public class TipoAcao {

        private int id;
        private String nome;
        private String obs;
        private Connection connection;
       
        public TipoAcao(Connection connection) {
                this.connection = CompossuiDriver.getConnection(); // pega conexão com banco.
        }
        public void save () {
            try {
                  Statement statement = connection.createStatement();
                  int i = statement.executeUpdate("UPDATE TipoAcao "
                      + "SET nome='"  + getNome() + "', "
                      + "obs='"  + getObs() + "'"
                      + "WHERE id = " + getId());
                } catch (SQLException insertException) {
                  System.out.println(insertException.toString());
                }
      }

       
        public void delete() throws SQLException {
            Statement statement = connection.createStatement();
            int i = statement.executeUpdate("DELETE FROM TipoAcao WHERE id =
" + getId());
        }
       
        public void insert() {
            try {
                  Statement statement = connection.createStatement();
                  int i = statement.executeUpdate("INSERT INTO TipoAcao " +
                  "(nome, obs) VALUES ('"
                      + getNome () + "', '"
                      + getObs() + "')");
       
       
                } catch (SQLException insertException) {
                    System.out.println(insertException.toString());
                }
       
        }
       

        public Connection getConnection() {
        return connection;
    }
    public void setConnection(Connection connection) {
        this.connection = connection;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getObs() {
        return obs;
    }
    public void setObs(String obs) {
        this.obs = obs;
    }

    /* (non-Javadoc)
     * @see ca.odell.glazedlists.TextFilterable#getFilterStrings(java.util.List)
     */
    public void getFilterStrings(List baseList) {
        baseList.add(getNome());
    }
}

     Here's how I'm loading information in my JTable:

// this method loads all data from Table to the ArrayList
private ArrayList loadTipoAcaos() {
        this.tipoacaos = new ArrayList();
        try {
            String sql = "SELECT * FROM TipoAcao ORDER BY Nome";
            Statement stm = CompossuiDriver.getConnection().createStatement();
            ResultSet rSet = null;

            rSet = stm.executeQuery(sql);


            while (rSet.next()) {
                TipoAcao tipoacao = new TipoAcao(this.getConnection());
                tipoacao.setId(rSet.getInt("id"));
                tipoacao.setNome(rSet.getString("nome"));
                tipoacao.setObs(rSet.getString("obs"));
                this.tipoacaos.add(tipoacao);
            }

            System.out.println("tipoacaos(s) carregado(s): [" +
tipoacaos.size() + "]\n");
            rSet.close();
            stm.close();
        }
        catch (SQLException e) {
            System.err.println("\n ERRO SQL: " + e.toString() + "\n");
        }
           return tipoacaos;
    }


// this method returns the JTable with the sorted information from the
ArrayList.
protected JTable createJTable() {

        tipoacaos = loadTipoAcaos();
        tipoacaoListEvt = new BasicEventList(tipoacaos);
        sortedTipoAcaos = new SortedList (tipoacaoListEvt, new
TipoAcaoComparator());
        // linhas = sortedTipoAcaos, colunas = TipoAcaoTable().
        filteredTipoAcaos = new TextFilterList(tipoacaoListEvt);
        etm = new EventTableModel(filteredTipoAcaos, new TipoAcaoTable());
        tfbusca = filteredTipoAcaos.getFilterEdit();
        JTable jtable = new JTable(etm);
        EventSelectionModel myEventSelectionModel = new
EventSelectionModel(tipoacaoListEvt);
        jtable.setSelectionModel(myEventSelectionModel);
        TableComparatorChooser tcs = new
TableComparatorChooser(jtable, sortedTipoAcaos, true);
        jtable.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
                if (e.getClickCount() == 2){
                    try {
                        showTipoAcaoDialog((byte)0);
                    } catch (SQLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }
        } );
        return jtable;
    }


   OK, the information is displayed on the JTable, but all my
operations (Insert, Update and Delete) to the DB are made from the
Bean, directly to the DB. The DB gets updated, but not the JTable.

   I've been trying hard to fix this - I believe I need to refresh the
ArrayList which caches the information represented in the JTable(?).

   Any clues would be appreciated.

cheers,
--
  .''`.  -- Breno Jacinto
: :´` : -- breno /at/ freeunix dot com dot br
: ' ' :  --  88AE 3F43 7110 57F6 A206
`. `'`   -- D116 02CA 02F4 803D 4294
  `--   -- Debian GNU/Linux - The Universal OS

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]

Reply | Threaded
Open this post in threaded view
|

Re: Updating JTable data

James Lemieux
Mr B J D d C,
 
     You are correct, for your JTable to have a chance at updating itself, glazedlists must be aware of changes that happen to the elements of its EventList. (In your case I'm speaking about tipoacaoListEvt - the BasicEventList which contains the elements you are persisting to your DB).
 
     There are a few ways to get that to happen:
 
1. Each time you call insert() save() or delete() on your beans and the method call succeeds, locate the bean within the BasicEventList (i.e. indexOfUpdate = tipoacaoListEvt.indexOf(freshlyUpdatedBean) and then
 
     i) in the case of insert() or save() call tipoacaoListEvt.set(indexOfUpdate, freshlyUpdatedBean)
 
     ii) in the case of delete() call tipoacaoListEvt.remove(indexOfUpdate)
 
2. A slightly less manual way to do this is to make your "Bean" a true Java Bean by making it observable via a PropertyChangeListener. Then, in your GlazedList pipeline, between your BasicEventList and SortedList, use an ObservableElementList in between them which listens for changes. For a comprehensive screencast on how to use an ObservableElementList, see http://www.publicobject.com/glazedlistsdeveloper/
 
Note: you'll have to invent something for handling the delete() case, since ObservableElementList only aids in propagating CHANGES TO ELEMENTS, but cannot detect CHANGES TO LIST STRUCTURE. (i.e. when an element should be removed)
 
3. Write your own EventList (by extending TransformedList) which wraps BasicEventList. All delete, insert, and save calls are routed through your custom EventList which first asks the element to delete, insert, or save itself appropriately from the DB, and then broadcasts the correct ListEvent describing the list change.
 
 
Overall, I think 1 is prone to accidental mistakes, 2. is probably the easiest solution to code with the most documentation available to aid you, and 3 is probably the most "industrial strength" but hardest to do because you'll have to get your hands a little dirty (though not much) with the inner workings of EventLists and the ListEvent model.
 
Hope that helps,
 
James.
 
On 10/11/05, Breno Jacinto Duarte da Costa <[hidden email]> wrote:
Hello guys,

   I've been using Glazed Lists for a month or so, and I must thank
and congratulate everyone in this project - it's awesome!!

   I'm posting here as I have searched google extensively, but got no
answer to my issue. I'm using a JTable within a JFrame, to display
data from a DB. When the user double clicks on the selected row,
there's a JDialog with the information of row, in form view. Then the
user may change some information and save it - thats the catch.

   Here's the bean that represents a row in my table:

public class TipoAcao {

       private int id;
       private String nome;
       private String obs;
       private Connection connection;

       public TipoAcao(Connection connection) {
               this.connection = CompossuiDriver.getConnection(); // pega conexão com banco.
       }
       public void save () {
           try {
                 Statement statement = connection.createStatement();
                 int i = statement.executeUpdate("UPDATE TipoAcao "
                     + "SET nome='"  + getNome() + "', "
                     + "obs='"           + getObs() + "'"
                     + "WHERE id = " + getId());
               } catch (SQLException insertException) {
                 System.out.println(insertException.toString());
               }
     }


       public void delete() throws SQLException {
           Statement statement = connection.createStatement();
           int i = statement.executeUpdate("DELETE FROM TipoAcao WHERE id =
" + getId());
       }

       public void insert() {
           try {
                 Statement statement = connection.createStatement ();
                 int i = statement.executeUpdate("INSERT INTO TipoAcao " +
                               "(nome, obs) VALUES ('"
                     + getNome () + "', '"
                     + getObs() + "')");


               } catch (SQLException insertException) {
                   System.out.println(insertException.toString());
               }

       }


       public Connection getConnection() {
       return connection;
   }
   public void setConnection(Connection connection) {
       this.connection = connection;
   }
   public int getId() {
       return id;
   }
   public void setId(int id) {
       this.id = id;
   }
   public String getNome() {
       return nome;
   }
   public void setNome(String nome) {
       this.nome = nome;
   }
   public String getObs() {
       return obs;
   }
   public void setObs(String obs) {
       this.obs = obs;
   }

   /* (non-Javadoc)
    * @see ca.odell.glazedlists.TextFilterable#getFilterStrings(java.util.List)
    */
   public void getFilterStrings(List baseList) {
       baseList.add(getNome());
   }
}

    Here's how I'm loading information in my JTable:

// this method loads all data from Table to the ArrayList
private ArrayList loadTipoAcaos() {
       this.tipoacaos = new ArrayList();
       try {
           String sql = "SELECT * FROM TipoAcao ORDER BY Nome";
           Statement stm = CompossuiDriver.getConnection ().createStatement();
           ResultSet rSet = null;

           rSet = stm.executeQuery(sql);


           while (rSet.next()) {
               TipoAcao tipoacao = new TipoAcao(this.getConnection());
               tipoacao.setId(rSet.getInt("id"));
               tipoacao.setNome(rSet.getString("nome"));
               tipoacao.setObs(rSet.getString("obs"));
               this.tipoacaos.add (tipoacao);
           }

           System.out.println("tipoacaos(s) carregado(s): [" +
tipoacaos.size() + "]\n");
           rSet.close();
           stm.close();
       }
       catch (SQLException e) {
           System.err.println("\n ERRO SQL: " + e.toString() + "\n");
       }
          return tipoacaos;
   }


// this method returns the JTable with the sorted information from the
ArrayList.
protected JTable createJTable() {

       tipoacaos = loadTipoAcaos();
       tipoacaoListEvt = new BasicEventList(tipoacaos);
       sortedTipoAcaos = new SortedList (tipoacaoListEvt, new
TipoAcaoComparator());
       // linhas = sortedTipoAcaos, colunas = TipoAcaoTable().
       filteredTipoAcaos = new TextFilterList(tipoacaoListEvt);
       etm = new EventTableModel(filteredTipoAcaos, new TipoAcaoTable());
       tfbusca = filteredTipoAcaos.getFilterEdit();
       JTable jtable = new JTable(etm);
       EventSelectionModel myEventSelectionModel = new
EventSelectionModel(tipoacaoListEvt);
       jtable.setSelectionModel (myEventSelectionModel);
       TableComparatorChooser tcs = new
TableComparatorChooser(jtable, sortedTipoAcaos, true);
       jtable.addMouseListener(new MouseAdapter(){
           public void mouseClicked(MouseEvent e){
               if (e.getClickCount() == 2){
                   try {
                       showTipoAcaoDialog((byte)0);
                   } catch (SQLException e1) {
                       // TODO Auto-generated catch block
                       e1.printStackTrace();
                   }
               }
           }
       } );
       return jtable;
   }


  OK, the information is displayed on the JTable, but all my
operations (Insert, Update and Delete) to the DB are made from the
Bean, directly to the DB. The DB gets updated, but not the JTable.

  I've been trying hard to fix this - I believe I need to refresh the
ArrayList which caches the information represented in the JTable(?).

  Any clues would be appreciated.

cheers,
--
.''`.  -- Breno Jacinto
: :´` : -- breno /at/ freeunix dot com dot br
: ' ' :  --  88AE 3F43 7110 57F6 A206
`. `'`   -- D116 02CA 02F4 803D 4294
`--   -- Debian GNU/Linux - The Universal OS

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]