0

Hi I want to fetch data from database and display into JTable. How can I achieve this?

Here is my table query for table:

select id,name,father from  employee

Here is my code:

public static void main( String[] str ) {
        String[] colName = new String[] { "Product Name" ,"Price" };
        Object[][] products = new Object[][] {
                { "Galleta" ,"$80" },
                { "Malta" ,"$40" },
                { "Nestea" ,"$120" }
          };

        JTable table = new JTable( products, colName );
        JFrame frame = new JFrame( "Simple Table Example" );
        // create scroll pane for wrapping the table and add
        // it to the frame
        frame.add( new JScrollPane( table ) );
        frame.pack();
        frame.setVisible( true );
    }
1
  • 1
    Either use a ResultSetTableModel (search on that term), or iterate the result set and put each entry into a custom table model of your own. Commented Nov 12, 2014 at 11:14

1 Answer 1

1

We can use Vector here

Code as follows

        Dbconnection obj=new Dbconnection();
        rs=obj.getWorkers();// rs is ResultSet object And getWorkers() is just a method in class Dbconnection
        Vector v1=new Vector();
        v1.addElement("ID");   //column name in JTable
        v1.addElement("NAME"); //column name in JTable
        v1.addElement("STATE"); //column name in JTable
        v1.addElement("MOB");   //column name in JTable
        Vector v3=new Vector(); //column name  in JTable 
        try{
        while(rs.next())
        {
            Vector v2=new Vector();
            v2.addElement(rs.getString(8));  // 8 is column number,And it depends on your query 
            v2.addElement(rs.getString(2));  // 2 is column number,And it depends on your query
            v2.addElement(rs.getString(6));  // 6 is column number,And it depends on your query
            v2.addElement(rs.getString(7)); // 7 is column number,And it depends on your query
        v3.add(v2);
        }
        }catch(Exception e){}
        JTable wrkr_table=new JTable(v3, v1);
        wrkr_table.setBackground(Color.PINK);
        JScrollPane scp=new JScrollPane(wrkr_table);
        scp.setBounds(50,100,680,110);
        frame.add(scp);   

Reffer Vector

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.