participate


Swing - About JTable.
This question is answered. Correct Answer available

<<   Back to Forum  |   Give us Feedback
This topic has 5 replies on 1 page.
HeavenBoy
Posts:34
Registered: 2/7/09
About JTable.   
Nov 7, 2009 4:47 AM
 
 
Hello , Can anyone please give me a hint on how to use the ResultSet to populate the JTable from the database , I have my ResultSet ready but I'm confused about how to use it , do I have to create a String Array to hold each row , and another to hold the column names , or are there special methods in the ResultSet Class that I can use ?

I created an inner class to be the Table Model for my MyTable class , but here the IDE underlines the columnName,rset variables in the methods ( getColumnCount() , getRowCount() ...) saying : "Cannot find symbol" ...Why so?


class MyTableModel extends AbstractTableModel {
 
 
public MyTableModel(){
 
    String columnName;
    ResultSet rset = MyTable.useConnAndGetData();
 
    try
    {
 
 
         ResultSetMetaData rsmd = rset.getMetaData();
         int numColumns = rsmd.getColumnCount();
 
        // Get the column names; column indices start from 1
        for (int i=1; i<numColumns+1; i++) {
            columnName = rsmd.getColumnName(i);
 
            // Get the name of the column's table name
            //String tableName = rsmd.getTableName(i);
        }
    }
    catch (SQLException e)
    {
        System.out.println(e.getMessage());
    }
 
}
 
        public int getColumnCount() {
            return columnName.getMetaData();
        }
 
        public int getRowCount() {
            return rset.getFetchSize();
        }
 
        public String getColumnName(int col) {    // confused about this..
            return columnName[col];
        }
 
        public Object getValueAt(int row, int col) {
            return rset[row][col];
        }
 
}


Thanks...
 
DarrylBurke
Posts:15,598
Registered: 7/2/07
Re: About JTable.   
Nov 7, 2009 5:08 AM (reply 1 of 5)  (In reply to original post )
 
 
the IDE underlines the columnName,rset variables in the methods ( getColumnCount() , getRowCount() ...) saying : "Cannot find symbol" ...Why so?
Because they're local variables declared in the constructor, not instance fields.

db
 
HeavenBoy
Posts:34
Registered: 2/7/09
Re: About JTable.   
Nov 7, 2009 6:27 AM (reply 2 of 5)  (In reply to #1 )
 
 
Okay , I got the answer from another thread , but now when I run this code the IDE says "running" and nothing is happening , no excpetions thrown or anything ,
the progress bar just keeps on going , Why is that happening ?

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
 
public class MyTable extends JPanel {
 
public MyTable()
 
{
 
final ResultSetTableModel model = new ResultSetTableModel();
JTable myTable = new JTable(model);
myTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
myTable.setFillsViewportHeight(true);
 
JScrollPane pane = new JScrollPane(myTable);
 
JPanel mainPanel = new JPanel();
mainPanel.add(pane);
mainPanel.setOpaque(true);
 
    JFrame frame = new JFrame("My Table Demo");
    frame.setSize(400, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // frame.setContentPane(new MyTable());
    frame.pack();
    frame.add(mainPanel);
 
    try
    {
    model.setResultSet(useConnAndGetData());
    }
    catch(SQLException e)
    {
    e.getMessage();
    }
}
 
      
  private static Connection getConnection()
       {
 
    Connection con = null;
 
     try
        {
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);   //registering JDBC Driver
        String serverName = "localhost";
        String portNumber = "1521";
        String sid = "mydb";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String user = "fundinfo";
        String pw = "tadapps";
 
        con = DriverManager.getConnection(url, user, pw);
        }
 
     catch (ClassNotFoundException e) {
                                    System.out.println(e.getMessage());
                                    System.exit(0);
                                      }
     catch (SQLException e) {
                              System.out.println(e.getMessage());
                              System.exit(0);
                             }
    return con;
 
       }
 
 
    public static ResultSet useConnAndGetData()
    {
 
        Connection con = getConnection();
    try
         {
         Statement stmt = con.createStatement();
         String select = "select title,year,price from movie order by year";
         ResultSet rows = stmt.executeQuery(select);
         return rows;
       }
    catch(SQLException e) {
             System.out.println(e.getMessage());
            }
        return null;
 
 }
 
    public static void main (String[] args)
    {  
                try
                {
                  new MyTable().setVisible(true);
                }
                catch (Exception ex)
                {
                    System.err.println(ex.getMessage());
                    ex.printStackTrace();
                }
    }
}
 
 
class ResultSetTableModel extends AbstractTableModel {
    // Currently displayed result set
    private ResultSet rs;
    // Associated metadata
    private ResultSetMetaData rsMeta;
    // Column count
    private int columnCount;
    // Column nmaes
    private final Vector<String> columnNames = new Vector<String>();
    // Vector of rows
    private final Vector<Object[]> cache = new Vector<Object[]>();
    
    /** Set new result set */
    public void setResultSet(ResultSet rs)
            throws SQLException
    {
        if (this.rs != null)
            this.rs.close();
        cache.clear();
        // 'Cache' some metadata data
        rsMeta = rs.getMetaData();
        columnCount = rsMeta.getColumnCount();
        columnNames.clear();
        for(int col = columnCount; col > 0; col--) {
            columnNames.add(rsMeta.getColumnName(col));
        }
        // 'Cache' new resultest data
        while(rs.next()) {
            Object rowData[] = new Object[columnCount];
            for(int col = columnCount; col > 0; col--)
                rowData[col - 1] = rs.getObject(col);
            cache.add(rowData);
        }
        // Reload table structure
        fireTableStructureChanged();
    }
    /** Close result set */
    public void close() throws SQLException {
        rs.close();
    }
    /** ## TableModel interface ## */
    public String getColumnName(int column) {
        return columnNames.get(column);
    }
    /** ## TableModel interface ## */
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object[] row = cache.get(rowIndex);
        return row[columnIndex];
    }
    /** ## TableModel interface ## */
    public int getRowCount() {
        return cache.size();
    }
    /** ## TableModel interface ## */
    public int getColumnCount() {
        return columnCount;
    }
}
 
kakaelement
Posts:46
Registered: 9/23/09
Re: About JTable.   
Nov 7, 2009 7:03 AM (reply 3 of 5)  (In reply to #2 )
 
 
in your database ,are there some datas in it?


HeavenBoy wrote:
Okay , I got the answer from another thread , but now when I run this code the IDE says "running" and nothing is happening , no excpetions thrown or anything ,
the progress bar just keeps on going , Why is that happening ?

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
 
public class MyTable extends JPanel {
 
public MyTable()
 
{
 
final ResultSetTableModel model = new ResultSetTableModel();
JTable myTable = new JTable(model);
myTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
myTable.setFillsViewportHeight(true);
 
JScrollPane pane = new JScrollPane(myTable);
 
JPanel mainPanel = new JPanel();
mainPanel.add(pane);
mainPanel.setOpaque(true);
 
    JFrame frame = new JFrame("My Table Demo");
    frame.setSize(400, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // frame.setContentPane(new MyTable());
    frame.pack();
    frame.add(mainPanel);
 
    try
    {
    model.setResultSet(useConnAndGetData());
    }
    catch(SQLException e)
    {
    e.getMessage();
    }
}
 
      
  private static Connection getConnection()
       {
 
    Connection con = null;
 
     try
        {
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);   //registering JDBC Driver
        String serverName = "localhost";
        String portNumber = "1521";
        String sid = "mydb";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String user = "fundinfo";
        String pw = "tadapps";
 
        con = DriverManager.getConnection(url, user, pw);
        }
 
     catch (ClassNotFoundException e) {
                                    System.out.println(e.getMessage());
                                    System.exit(0);
                                      }
     catch (SQLException e) {
                              System.out.println(e.getMessage());
                              System.exit(0);
                             }
    return con;
 
       }
 
 
    public static ResultSet useConnAndGetData()
    {
 
        Connection con = getConnection();
    try
         {
         Statement stmt = con.createStatement();
         String select = "select title,year,price from movie order by year";
         ResultSet rows = stmt.executeQuery(select);
         return rows;
       }
    catch(SQLException e) {
             System.out.println(e.getMessage());
            }
        return null;
 
 }
 
    public static void main (String[] args)
    {  
                try
                {
                  new MyTable().setVisible(true);
                }
                catch (Exception ex)
                {
                    System.err.println(ex.getMessage());
                    ex.printStackTrace();
                }
    }
}
 
 
class ResultSetTableModel extends AbstractTableModel {
    // Currently displayed result set
    private ResultSet rs;
    // Associated metadata
    private ResultSetMetaData rsMeta;
    // Column count
    private int columnCount;
    // Column nmaes
    private final Vector<String> columnNames = new Vector<String>();
    // Vector of rows
    private final Vector<Object[]> cache = new Vector<Object[]>();
    
    /** Set new result set */
    public void setResultSet(ResultSet rs)
            throws SQLException
    {
        if (this.rs != null)
            this.rs.close();
        cache.clear();
        // 'Cache' some metadata data
        rsMeta = rs.getMetaData();
        columnCount = rsMeta.getColumnCount();
        columnNames.clear();
        for(int col = columnCount; col > 0; col--) {
            columnNames.add(rsMeta.getColumnName(col));
        }
        // 'Cache' new resultest data
        while(rs.next()) {
            Object rowData[] = new Object[columnCount];
            for(int col = columnCount; col > 0; col--)
                rowData[col - 1] = rs.getObject(col);
            cache.add(rowData);
        }
        // Reload table structure
        fireTableStructureChanged();
    }
    /** Close result set */
    public void close() throws SQLException {
        rs.close();
    }
    /** ## TableModel interface ## */
    public String getColumnName(int column) {
        return columnNames.get(column);
    }
    /** ## TableModel interface ## */
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object[] row = cache.get(rowIndex);
        return row[columnIndex];
    }
    /** ## TableModel interface ## */
    public int getRowCount() {
        return cache.size();
    }
    /** ## TableModel interface ## */
    public int getColumnCount() {
        return columnCount;
    }
}
 
HeavenBoy
Posts:34
Registered: 2/7/09
Re: About JTable.   
Nov 7, 2009 7:23 AM (reply 4 of 5)  (In reply to #3 )
 
 
Yes there is data , I run the same query in the database and there is data ....
 
camickr
Posts:32,733
Registered: 2/27/98
Re: About JTable.   
Nov 7, 2009 9:04 AM (reply 5 of 5)  (In reply to #2 )
Correct
 
frame.pack();
frame.add(mainPanel);


should be:

frame.add(mainPanel);
frame.pack();
frame.setVisible();


You can also check out Table From Database for a little more generic solution. Thats supports different data types in each column.
 
This topic has 5 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums