I seem to have a problem refreshing the data within my JTable. I know the code is being run through.
I have a JTable which is populated from a selection in a combo box, on first click within the combo box the table displays the correct data.
So basically the data within the JTable doesnt refresh. :(
So please help me to use the current JTable to display different query results on it.

The whole code that Im using is :

package mypackage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;


public class Bes extends JFrame { 
	
	private ResultSetTableModel tableModel;   // class definition presented at the end of the code
    private JTabbedPane tabbedpane = new JTabbedPane();
    private JComboBox comboBox = new JComboBox();
    private JComboBox comboBox1 = new JComboBox();    
    private JLabel label = new JLabel("Select the requested item from comboboxes."); 
    private JPanel panel = new JPanel();

	
    public Bes() {
        initUI();         
      
    }
    public void conn(String driver,String dbName,String url,String query) 
    {
    	// *********************************************************************************************************    	
    
	        // create ResultSetTableModel and display database table
	        try {
	           // create TableModel for results of query
	           tableModel = new ResultSetTableModel( driver, url, query );
	           JTable resultTable = new JTable( tableModel );
	        
	           
	         // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  Jtable   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	           
	           panel.setLayout(null); 
	           panel.add( new JScrollPane( resultTable ),BorderLayout.NORTH);
	           resultTable.setFillsViewportHeight(true);
	           resultTable.setBounds(60,200,400,50);                              
	           //Box box = Box.createHorizontalBox();
	           panel.add(resultTable);
	        }
	        catch ( ClassNotFoundException classNotFound ) {
	           JOptionPane.showMessageDialog( null,
	              "Clientdriver bulunamadı", "Driver bulunamadı",
	              JOptionPane.ERROR_MESSAGE );
	           
	           System.exit( 1 );   
	        }
	        
	        catch ( SQLException sqlException ) {
	           JOptionPane.showMessageDialog( null,
	              sqlException.toString(), 
	              "Veritabanı hatası", JOptionPane.ERROR_MESSAGE );
	           
	           System.exit( 1 );   
	        }        
	        
   		        driver = "";  // i tried to reset conn fnc' parameters
   		        dbName=" ";  // before calling again
   		        url =" ";
   		        query = " "; 
	        
//**********************************************************************************************************************    	
   	
    	
    }
    public void initUI() { 
    	 	
        panel.setLayout(null);
        panel.setBackground(Color.white);
        comboBox.addItem(" Vitamin ");
        comboBox.addItem("Vitamin_A_retinol");
        comboBox.addItem("Vitamin_B1_thiamin");
        comboBox.addItem("Vitamin_B2_riboflavin");
        comboBox.addItem("Niasin");
        comboBox.addItem("Vitamin B5 (pantotenik asit)");
        comboBox.addItem("Vitamin B6");
        comboBox.addItem("Vitamin B12");
        comboBox.addItem("Vitamin C");
        
        comboBox1.addItem("Mineral ");
        comboBox1.addItem("Bakır");
        comboBox1.addItem("Cinko");
        comboBox1.addItem("Demir");
        comboBox1.addItem("Florit");
        comboBox1.addItem("Folat");
        comboBox1.addItem("Fosfor");
        comboBox1.addItem("İyot");
        comboBox1.addItem("Kalsiyum");
     
        panel.add(comboBox); 
        panel.add(comboBox1);       
        panel.add(label);
        comboBox.setBounds(60, 60, 190, 30);
        comboBox1.setBounds(300, 60, 150, 30);  
        label.setBounds(60, 15, 300, 30); 
        tabbedpane.setBounds(0, 200, 300, 100);
       
       getContentPane().add(tabbedpane, BorderLayout.CENTER);
       tabbedpane.addTab(" Vitamin / Mineral ", panel);

  
       JButton quitButton = new JButton("ex-it");
       quitButton.setBounds(60, 560, 80, 30);
       
       ActionListener actionListener = new ActionListener() {
   		public void actionPerformed (ActionEvent e)   
   		{
   			if (e.getSource () == comboBox)  
   				
   			{  		
   				String v = (String)comboBox.getSelectedItem();
   			   
   			    System.out.println(v); 
   			    
   		        String driver = "org.apache.derby.jdbc.ClientDriver";
   		        
   		        // URL to connect to books database
   		         String dbName="seconddb";
   		         String url ="jdbc:derby://localhost:1527/" + dbName +";create=true";
   		        
   		        // query to select entire authors table
   		        String query = "SELECT FOOD_NAME,"+v+" FROM FOODTABLET ";  
   		        
   			    conn(driver,dbName,url,query);

   			}  // END İF1
  			 			
   			
   			if (e.getSource () == comboBox1)  
   			{  String v = (String)comboBox1.getSelectedItem();
   			System.out.println(v); 
   			}
   		}
	};      
	comboBox.addActionListener(actionListener);
	comboBox1.addActionListener(actionListener);
       
       // 
       quitButton.addActionListener( new ActionListener() {
           public void actionPerformed(ActionEvent event) {
               System.exit(0);
          }
           });     
       // 
       
       panel.add(quitButton);    
       setTitle("Demo1");
       setSize(600, 720);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }  // end initUI

    public static void main(String[] args) {
    	  	
    	
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	Bes ex = new Bes();  //
                ex.setVisible(true);         // 
            }
            
        });
    }

    
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ResultSetTableModel tableModel;   // related class definition : 
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@


import java.sql.*;
import java.util.*;

// Java extension packages
import javax.swing.table.*;
// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).

public class ResultSetTableModel extends AbstractTableModel {

private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData metaData;
private int numberOfRows;
  // initialize resultSet and obtain its meta data object;
  // determine number of rows

public ResultSetTableModel( String driver, String url, 
     String query ) throws SQLException, ClassNotFoundException
  {
	
     // load database driver class
     Class.forName( driver );
     // connect to database
     connection = DriverManager.getConnection( url );
     // create Statement to query database
     statement = connection.createStatement( 
        ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY 
        );  
     // set query and execute it
     setQuery( query );
     
     
  }
  // get class that represents column type
public Class getColumnClass( int column )
  {
     // determine Java class of column
     try {
        String className = 
           metaData.getColumnClassName( column + 1 );
        
        // return Class object that represents className
        return Class.forName( className );
     }
     
     // catch SQLExceptions and ClassNotFoundExceptions
     catch ( Exception exception ) {
        exception.printStackTrace();
     }
     
     // if problems occur above, assume type Object 
     return Object.class;
  }
  // get number of columns in ResultSet
public int getColumnCount() 
  {      
     // determine number of columns
     try {
        return metaData.getColumnCount(); 
     }
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems occur above, return 0 for number of columns
      return 0;
   }
   // get name of a particular column in ResultSet
public String getColumnName( int column )
   {       
      // determine column name
      try {
         return metaData.getColumnName( column + 1 );  
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems, return empty string for column name
      return "";
   }
   // return number of rows in ResultSet
public int getRowCount() 
   { 
      return numberOfRows;
   }
   // obtain value in particular row and column
public Object getValueAt( int row, int column )
   { 
      // obtain a value at specified ResultSet row and column
      try {
         resultSet.absolute( row + 1 );
         
         return resultSet.getObject( column + 1 );
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems, return empty string object
      return "";
   }
   // close Statement and Connection
protected void finalize()
   {
      // close Statement and Connection
      try {
         statement.close();
         connection.close();
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
   }
   // set new database query string
public void setQuery( String query ) throws SQLException 
   {
	  // resultSet.deleteRow();          not works!
      // specify query and execute it
      resultSet = statement.executeQuery( query );
      // obtain meta data for ResultSet
      metaData = resultSet.getMetaData();
      // determine number of rows in ResultSet
      resultSet.last();                   // move to last row
      numberOfRows = resultSet.getRow();  // get row number   
      
      // notify JTable that model has changed
      fireTableStructureChanged();
   }
} // end class ResultSetTableModel

Hello,
Firstly a post is the correct option in which you should be asking for help. Code Snippets are rather ways to show your already working* code.

Second of all, I would assume that the Jtable is being repeatedly added to the JPanel which are rather being accumilated on the bottom of each other. And it is not visible in your screen.

I think you would like to use the removeAll() method to destroy all the objects that are currently in the panel and then re-draw ( add )the next Jtable.

Hope it works.

No need to remove or create new JTables at all. Change the data that is within the model instead.

It looks like you can call setQuery() on your ResultSetTableModel to query a new set of data. If you maintain a single instance of that model, you can just update it's query when your combobox selection changes.

No need to remove or create new JTables at all. Change the data that is within the model instead.

It looks like you can call setQuery() on your ResultSetTableModel to query a new set of data. If you maintain a single instance of that model, you can just update it's query when your combobox selection changes.

AS FAR AS I ASSUME The OP seems to be creating a new instance of the Jtable everytime the actionPerformed() method is being called. Thereby I assumed that remove would be the appropriate fix. Correct me If I am wrong.

You are correct that they are adding a new JTable every time, but the solution is not to remove those tables before adding the new one. The solution is to keep one JTable.

There is absolutely no need to create a new table just to update the data. The data is the model's responsibility and that is all that needs to change here. There is even a method to change the query without creating a new ResultSetTableModel, so it's simply a matter of calling that method on the existing model instance with a new query string.

Agreed. Lol, I was going on an approach of creating a sub-panel that would hold the Jtable. And then, removeAll and Add the new Jtable.
I didn't notice setQuery().

Thank you guys but how/where should i use holy setQuery() method at all ??

I would recommend moving the table creation code out of conn() into your initUI() method.

Your action listener for the combo box then needs to initialize the table model if it is null or setQuery() with the new query string if the model has already been created.

When user clicks combobox second time the jtable data is not changing. Combobox's Action listener works, query works, table model works for the first time but i can't see any difference on JTable at second time or later.
Any help will be appreciated.

Edited 5 Years Ago by sheennave: n/a

Sorry for latency. Here it is.

package mypackage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;


public class Beslenmek extends JFrame { 
	
	private ResultSetTableModel tableModel;
	private JTabbedPane tabbedpane = new JTabbedPane();
    private JComboBox comboBox = new JComboBox();
    private JComboBox comboBox1 = new JComboBox();    
    private JLabel label = new JLabel("Select the requested item from comboboxes.");
    private JLabel label1 = new JLabel("Gıda Adı"); 
    private JLabel label2 = new JLabel("Vitamin");
    private JPanel panel = new JPanel();
    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    String driver = "org.apache.derby.jdbc.ClientDriver"; String dbName="seconddb"; String url="jdbc:derby://localhost:1527/" + dbName +";create=true";
    String query="SELECT * FROM GIDATABLET";  // INITIAL VALUES 
	
    public Beslenmek() {
    
    	initUI(driver,dbName,url,query); 
      
    }
    	     
    public void initUI(String driver,String dbName,String url,String query) { 
    	
    	// *********************************************************************************************************    	
        
	        // create ResultSetTableModel and display database table
	        try {
	           // create TableModel for results of query
	           tableModel = new ResultSetTableModel( driver, url, query );
	           JTable resultTable = new JTable( tableModel );
	              
	           panel.setLayout(null); 
	           panel.add( new JScrollPane( resultTable ),BorderLayout.NORTH);
	           resultTable.setFillsViewportHeight(true);
	           resultTable.setBounds(60,200,400,50);                              
	           //Box box = Box.createHorizontalBox();
	           panel.add(resultTable);
	        }
	        catch ( ClassNotFoundException classNotFound ) {
	           JOptionPane.showMessageDialog( null,
	              "Clientdriver bulunamadı", "Driver bulunamadı",
	              JOptionPane.ERROR_MESSAGE );
	           
	           System.exit( 1 );   // terminate application
	        }
	        
	        catch ( SQLException sqlException ) {
	           JOptionPane.showMessageDialog( null,
	              sqlException.toString(), 
	              "Veritabanı hatası", JOptionPane.ERROR_MESSAGE );
	           
	           System.exit( 1 );   // terminate application
	        }        
	        
   		        driver = "";
   		        dbName=" ";
   		        url =" ";
   		        query = " "; 
	        
//**********************************************************************************************************************      	
   		      
    	 	
        panel.setLayout(null);
        panel.setBackground(Color.white);
        comboBox.addItem(" Vitamin ");
        comboBox.addItem("Vitamin_A_retinol");
        comboBox.addItem("Vitamin_B1_thiamin");
        comboBox.addItem("Vitamin_B2_riboflavin");

        
        comboBox1.addItem("Mineral ");
        comboBox1.addItem("Bakır");

     
        panel.add(comboBox); 
        panel.add(comboBox1);       
        panel.add(label);
        panel.add(label1);
        panel.add(label2);
        comboBox.setBounds(60, 60, 190, 30);
        comboBox1.setBounds(300, 60, 150, 30);  
        label.setBounds(60, 15, 300, 30);
        label1.setBounds(60, 170, 300, 30); 
        label2.setBounds(155, 170, 300, 30); 
        tabbedpane.setBounds(0, 200, 300, 100);
       
       getContentPane().add(tabbedpane, BorderLayout.CENTER);
      
       tabbedpane.addTab(" Vitamin / Mineral ", panel);
       tabbedpane.addTab("G.Contents", panel1);
       tabbedpane.addTab("G.B.I", panel2);

  
       JButton quitButton = new JButton("ex-it");
       quitButton.setBounds(60, 560, 80, 30);
       
       ActionListener actionListener = new ActionListener() {
   		public void actionPerformed (ActionEvent e)   
   		{
   			if (e.getSource () == comboBox)  
   				
   			{  	
   				
   				// getContentPane().removeAll();    initUI();
   				String v = (String)comboBox.getSelectedItem();  
   			   
   			    System.out.println(v);   label2.setText("Vitamin");
   			    
   		    	String driver = "org.apache.derby.jdbc.ClientDriver";
   		        
   		        // URL to connect to books database
   		         String dbName="seconddb";
   		         String url ="jdbc:derby://localhost:1527/" + dbName +";create=true";
   		        
   		        // query to select entire authors table
   		        String query = "SELECT GIDA_ADI,"+v+" FROM GIDATABLET ";  
   		        
   		        initUI(driver,dbName,url,query); 
   			    	    
   			    
   			}  // END İF1
  			 			
   			
   			if (e.getSource () == comboBox1)  
   			{  String v = (String)comboBox1.getSelectedItem(); label2.setText("Mineral");
   			System.out.println(v); 
   			}
   		}
	};      
	comboBox.addActionListener(actionListener);
	comboBox1.addActionListener(actionListener);
       
       // 
       quitButton.addActionListener( new ActionListener() {
           public void actionPerformed(ActionEvent event) {
               System.exit(0);
          }
           });     
       // 
       
       panel.add(quitButton);    
       setTitle("Demo1");
       setSize(600, 720);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }  // end initUI

    public static void main(String[] args) {
    	 	
    	
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	Beslenmek ex = new Beslenmek();  //
                ex.setVisible(true);         // 
            }
            
        });
    }

    
}

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
tableModel   
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

package mypackage;
//Java core packages
import java.sql.*;
import java.util.*;
import java.util.EventObject;  // javax.swing.event.TableModelEvent
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;



// Java extension packages
import javax.swing.table.*;
// ResultSet rows and columns are counted from 1 and JTable 
// rows and columns are counted from 0. When processing 
// ResultSet rows or columns for use in a JTable, it is 
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is 
// ResultSet column 1 and JTable row 0 is ResultSet row 1).

public class ResultSetTableModel extends AbstractTableModel {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData metaData;
private int numberOfRows;
  // initialize resultSet and obtain its meta data object;
  // determine number of rows

public ResultSetTableModel( String driver, String url, 
     String query ) throws SQLException, ClassNotFoundException
  {
	
     // load database driver class
     Class.forName( driver );
     // connect to database
     connection = DriverManager.getConnection( url );
     // create Statement to query database
     statement = connection.createStatement( 
        ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_READ_ONLY 
        );  
     // set query and execute it
     setQuery( query );
     
     
  }
  // get class that represents column type
public Class getColumnClass( int column )
  {
     // determine Java class of column
     try {
        String className = 
           metaData.getColumnClassName( column + 1 );
        
        // return Class object that represents className
        return Class.forName( className );
     }
     
     // catch SQLExceptions and ClassNotFoundExceptions
     catch ( Exception exception ) {
        exception.printStackTrace();
     }
     
     // if problems occur above, assume type Object 
     return Object.class;
  }
  // get number of columns in ResultSet
public int getColumnCount() 
  {      
     // determine number of columns
     try {
        return metaData.getColumnCount(); 
     }
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems occur above, return 0 for number of columns
      return 0;
   }
   // get name of a particular column in ResultSet
public String getColumnName( int column )
   {       
      // determine column name
      try {
         return metaData.getColumnName( column + 1 );  
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems, return empty string for column name
      return "";
   }
   // return number of rows in ResultSet
public int getRowCount() 
   { 
      return numberOfRows;
   }
   // obtain value in particular row and column
public Object getValueAt( int row, int column )
   { 
      // obtain a value at specified ResultSet row and column
      try {
         resultSet.absolute( row + 1 );
         
         return resultSet.getObject( column + 1 );
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
      
      // if problems, return empty string object
      fireTableCellUpdated(row,column);  // F
      return "";
   }
   // close Statement and Connection
protected void finalize()
   {
      // close Statement and Connection
      try {
         statement.close();
         connection.close();
      }
      
      // catch SQLExceptions and print error message
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }
   }

   // *******set new database query string*********
public void setQuery( String query ) throws SQLException 
   {
      // specify query and execute it
      resultSet = statement.executeQuery( query );
      // obtain meta data for ResultSet
      metaData = resultSet.getMetaData();
      // determine number of rows in ResultSet
      resultSet.last();                   // move to last row
      numberOfRows = resultSet.getRow();  // get row number   
      
      // notify JTable that model has changed
      fireTableStructureChanged();  
      fireTableChanged(null);
   }

public void tableChanged(TableModelEvent e)
{   fireTableChanged(e);  }

} // end class ResultSetTableModel

Edited 5 Years Ago by sheennave: n/a

I recommended that you move the table creation code into initUI, not all of the database and model code. Create only your UI components in initUI(). Do not create your table model there. The entire point is to create the UI components only once.

In your action listener, create or update your table model. The model will initially be null, so you create it the first time a selection is made. If the model is not null, simply call setQuery() with the new query string.

Do NOT re-create your entire UI just because they selected a different value to query.

This question has already been answered. Start a new discussion instead.