Question

I m retriving an oracle table and displaying it in jtable.. This is d first time i m using jtable so i dont kno anything. i did my research and tried different methods but i cudnt underatsnd properly.. Its not displaying the data in jtable.

        DefaultTableModel model = new DefaultTableModel();
    jTable1 = new javax.swing.JTable(model);

if(evt.getSource()==jButton2){

        Connection conn=null;
        PreparedStatement ps=null;
       Vector<Vector<Object>> data = new Vector<Vector<Object>>();
Vector columns = new Vector();
     Statement stmt=null;

        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","hr");
        }
        catch(ClassNotFoundException | SQLException e)
        {

            System.out.println(e);
        }
        try{
            ps=conn.prepareStatement("select * from \"SYSTEM\".NEWUSER");

        ResultSet rs = ps.executeQuery();
        ResultSetMetaData md = rs.getMetaData();
        Vector<String> columnNames = new Vector<String>();
        int columnCount = md.getColumnCount();
         for (int i = 1; i <= columnCount; i++)
        {
            columnNames.addElement( md.getColumnName(i) );
        }
         columns.add(columnNames); 
         while (rs.next())
        {
             Vector<Object> row = new Vector<Object>();

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

            data.add( row );
            //System.out.println("watever");
        }

        rs.close();
        ps.close();
        conn.close();

             }
                    catch(SQLException | HeadlessException e)
        {

            System.out.println("the error is"+e);
        }
        JTable jTable1 = new JTable(data, columns);





}

I made the changes but its still not showing d data in the row..

Was it helpful?

Solution

DefaultTableModel model = new DefaultTableModel();

The code looks reasonable except the model contains no columns. Columns are not automatically created when you add a row of data.

Your code should be something like:

String[] columnNames = {"Column1", "Column2", "Column3", "Column4", "Column5"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);

Then when you add the rows you should see 5 columns of data.

Or for a better solution that will create the column names based on the SQL see the Table From Database Example code found in Table From Database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top