Results 1 to 5 of 5
  1. #1
    Cynot is offline Member
    Join Date
    May 2010
    Posts
    9
    Rep Power
    0

    Default [SOLVED] Ye Olde jTable Refresh Question...

    Feel free to call me a moron on this one (and maybe I am), but I have to ask this question.

    I know it has been asked before a million times, and I've searched through thread upon thread of us newbies asking about refreshing the contents of a jTable, but for some reason none of the methods I've tried seem to work.

    My situation is this:

    I have a simple Java / MySQL application where a jTable is displaying the contents of the database. I did this by (I'm using Netbeans BTW) dragging a jTable onto the main jPanel and then dragging the database connection onto the jTable binding them.

    This works all well and good, but of course I want the table to update when I add records into MySQL via another java window. The MySQL inputs/updates all work just fine, so what I need to do is re-execute the MySQL query and display the updated information in my jTable.

    Now, I was under the impression that the repaint() method would do what I need, but apparently it does nothing. So I tried messing with the fire action listeners, but I couldn't get that to work either.

    Basically to my mind, I must be making this far more complicated then it actually is. Is there a basic refresh method I can call to cause the jTable to re-execute its query etc? I just want it to update when I click "save" in my other java window which adds / updates the MySQL database.

    Essentially the only code I have that pertains to this jTable is the auto-generated code by Netbeans that's created when I added the jTable / bound it to my DB.


    If you're interested, here is the "initComponents()" method with the automatically generated code from NetBeans.

    -----------

    Java Code:
    private void initComponents() {
    
            bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
    
            mainPanel = new javax.swing.JPanel();
            masterScrollPane = new javax.swing.JScrollPane();
            participantsTable = new javax.swing.JTable();
            refreshButton = new javax.swing.JButton();
            addParticipantButton = new javax.swing.JButton();
            menuBar = new javax.swing.JMenuBar();
            javax.swing.JMenu fileMenu = new javax.swing.JMenu();
            jSeparator1 = new javax.swing.JSeparator();
            jSeparator2 = new javax.swing.JSeparator();
            javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
            javax.swing.JMenu helpMenu = new javax.swing.JMenu();
            javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
            statusPanel = new javax.swing.JPanel();
            javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
            statusMessageLabel = new javax.swing.JLabel();
            statusAnimationLabel = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(welcomehomev04.WelcomeHomeV04App.class).getContext().getResourceMap(WelcomeHomeV04View.class);
            entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory(resourceMap.getString("entityManager.persistenceUnit")).createEntityManager(); // NOI18N
            query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("query.query")); // NOI18N
            list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
    
            mainPanel.setName("mainPanel"); // NOI18N
            mainPanel.setLayout(null);
    
            masterScrollPane.setName("masterScrollPane"); // NOI18N
    
            participantsTable.setAutoCreateRowSorter(true);
            participantsTable.setName("participantsTable"); // NOI18N
    
            org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, participantsTable);
            org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${FName}"));
            columnBinding.setColumnName("FName");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${LName}"));
            columnBinding.setColumnName("LName");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone1}"));
            columnBinding.setColumnName("Phone1");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${ext}"));
            columnBinding.setColumnName("Ext");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
            columnBinding.setColumnName("Email");
            columnBinding.setColumnClass(String.class);
            columnBinding.setEditable(false);
            bindingGroup.addBinding(jTableBinding);
            jTableBinding.bind();
            participantsTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    participantsTableMouseClicked(evt);
                }
            });
            masterScrollPane.setViewportView(participantsTable);
            participantsTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title2")); // NOI18N
            participantsTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title4")); // NOI18N
            participantsTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("masterTable.columnModel.title5")); // NOI18N
            participantsTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("masterTable.columnModel.title6")); // NOI18N
            participantsTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("masterTable.columnModel.title8")); // NOI18N
    
            mainPanel.add(masterScrollPane);
            masterScrollPane.setBounds(10, 11, 730, 130);
    
            javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(welcomehomev04.WelcomeHomeV04App.class).getContext().getActionMap(WelcomeHomeV04View.class, this);
            refreshButton.setAction(actionMap.get("refresh")); // NOI18N
            refreshButton.setName("refreshButton"); // NOI18N
            mainPanel.add(refreshButton);
            refreshButton.setBounds(810, 130, 71, 23);
    
            addParticipantButton.setAction(actionMap.get("showParticipantDetails")); // NOI18N
            addParticipantButton.setText(resourceMap.getString("addParticipantButton.text")); // NOI18N
            addParticipantButton.setName("addParticipantButton"); // NOI18N
            mainPanel.add(addParticipantButton);
            addParticipantButton.setBounds(750, 20, 71, 23);
    
            menuBar.setName("menuBar"); // NOI18N
    
            fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
            fileMenu.setName("fileMenu"); // NOI18N
    
            jSeparator1.setName("jSeparator1"); // NOI18N
            fileMenu.add(jSeparator1);
    
            jSeparator2.setName("jSeparator2"); // NOI18N
            fileMenu.add(jSeparator2);
    
            exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
            exitMenuItem.setName("exitMenuItem"); // NOI18N
            fileMenu.add(exitMenuItem);
    
            menuBar.add(fileMenu);
    
            helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
            helpMenu.setName("helpMenu"); // NOI18N
    
            aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
            aboutMenuItem.setName("aboutMenuItem"); // NOI18N
            helpMenu.add(aboutMenuItem);
    
            menuBar.add(helpMenu);
    
            statusPanel.setName("statusPanel"); // NOI18N
    
            statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
    
            statusMessageLabel.setName("statusMessageLabel"); // NOI18N
    
            statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
    
            progressBar.setName("progressBar"); // NOI18N
    
            javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
            statusPanel.setLayout(statusPanelLayout);
            statusPanelLayout.setHorizontalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 923, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(statusMessageLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 753, Short.MAX_VALUE)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(statusAnimationLabel)
                    .addContainerGap())
            );
            statusPanelLayout.setVerticalGroup(
                statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(statusPanelLayout.createSequentialGroup()
                    .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(3, 3, 3))
            );
    
            setComponent(mainPanel);
            setMenuBar(menuBar);
            setStatusBar(statusPanel);
    
            bindingGroup.bind();
        }
    Last edited by Cynot; 05-26-2010 at 11:11 PM. Reason: solved

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    12,998
    Blog Entries
    7
    Rep Power
    19

    Default

    A JTable doesn't know it when its model has changed; it has to be notified about that fact. Repainting the table simply repaints the JTable if it needs to be repainted. If the EDT decides that it doesn't need repainting it isn't repainted. Try to use the tableChanged( ... ) method instead (read the API documentation for the JTable class).

    kind regards,

    Jos

  3. #3
    Cynot is offline Member
    Join Date
    May 2010
    Posts
    9
    Rep Power
    0

    Default

    Thanks JosAH,

    So, if I read the documentation correctly, I need the following:

    Java Code:
    TableModelEvent x = new TableModelEvent(participantsTable.getModel());
    
     participantsTable.tableChanged(x);
    Where participantsTable is the name of my jTable.

    The creation of the TableModelEvent(source) specifying that all the data has changed, and the tableChanged(TableModelEvent) method then notifying the participantsTable that there has been a change in the data correct?

  4. #4
    camickr is online now Senior Member
    Join Date
    Jul 2009
    Posts
    1,226
    Rep Power
    6

    Default

    so what I need to do is re-execute the MySQL query and display the updated information in my jTable.
    Yes, that is all you need to do. The easiest way to do this is to create a new TableModel from the updated query and then add the model to the table. The table will automatically repaint itself, you don't have to worry about firing events or anything.

    Java Code:
    TableModel model = new YourTableModel(...);
    table.setModel( model );

  5. #5
    Cynot is offline Member
    Join Date
    May 2010
    Posts
    9
    Rep Power
    0

    Default

    Thanks camickr!

    I was actually able to get that to work exactly as I needed. I reconfigured a TableModel with the settings I needed and called participantsTable.setModel(newModel). Now everything is refreshing just fine.

    I really appreciate the help!

    For those that may come searching for this in the future, the following link was also very helpful:

    Pasted code - Fill a Swing table from a MySQL query

    Java Code:
    (pasted from the above website)
    
    import java.awt.BorderLayout;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
     
    class MySQLTable
    {
     
      private static Connection con = null;
      private static String URL = "jdbc:mysql://serverHostName/DBName";
      private static String driver = "com.mysql.jdbc.Driver";
      private static String user = "DBUserName";
      private static String pass = "DBUserPassword";
     
      /**
       * Main aplication entry point
       * @param args
       * @throws SQLException
       */
      public static void main(String[] args) throws SQLException
      {
     
        // a MySQL statement
        Statement stmt;
        // a MySQL query
        String query;
        // the results from a MySQL query
        ResultSet rs;
     
        // 2 dimension array to hold table contents
        // it holds temp values for now
        Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3"}};
        // array to hold column names
        Object columnNames[] = {"Column One", "Column Two", "Column Three"};
     
        // create a table model and table based on it
        DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);
        JTable table = new JTable(mTableModel);
     
        // try and connect to the database
        try {
          Class.forName(driver).newInstance();
          con = DriverManager.getConnection(URL, user, pass);
        } catch (Exception e) {
          System.err.println("Exception: " + e.getMessage());
        }
     
        // run the desired query
        query = "SELECT colOne, colTwo, colThree FROM tableName";
        // make a statement with the server
        stmt = con.createStatement();
        // execute the query and return the result
        rs = stmt.executeQuery(query);
     
        // create the gui
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
     
        // remove the temp row
        mTableModel.removeRow(0);
     
        // create a temporary object array to hold the result for each row
        Object[] rows;
        // for each row returned
        while (rs.next()) {
          // add the values to the temporary row
          rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3)};
          // add the temp row to the table
          mTableModel.addRow(rows);
        }
     
      }

Similar Threads

  1. Jtable selection question
    By casid in forum New To Java
    Replies: 2
    Last Post: 02-04-2010, 07:11 PM
  2. Inside a Timer thread loop,how to refresh a JTable in swing
    By neha_negi in forum Threads and Synchronization
    Replies: 3
    Last Post: 09-04-2009, 01:45 AM
  3. Dynamic Refresh in JTable every 5 Minutes
    By britto_bicsjohn in forum AWT / Swing
    Replies: 3
    Last Post: 08-07-2009, 05:16 AM
  4. how to refresh data of the JTable
    By paty in forum JDBC
    Replies: 3
    Last Post: 08-17-2008, 12:01 PM
  5. Simple question of JTable
    By carl in forum AWT / Swing
    Replies: 1
    Last Post: 08-07-2007, 07:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •