populating a JTable with two columns while having the database id accessible

Hi, new to using JTable, and since in a rush to finish this piece in the next hour, hence the 500points. I have a JTable and I want to populate it with two clumns First Name, Last Name. Data is coming from the database . I want to be able to click on one row and get the database ID of the row so I can use it elsewhere.  If I was using a JList, I would create a vector of PairElement class [below] and assign it to the list, but since I need to display two columns, I will use JTable. Any working suggestion plz? To be simple, here is the data to be displayed

columnNames = { "first Name ", "Last Name"};

rows:
FirstName1, LastName1  //database id 100
FirstName2, LastName2 //database id 101

When I click on the first raw, I wanna be able to get the id 100.  So what is the common approach to do this in JTable?
 
public class PairElement
{
    protected String m_name;
    protected String m_id;

    public PairElement(String name, String id)
    {
     m_name = name;
     m_id = id;
    }

    public void   setName(String name) {
      m_name = name;
    }
   
    public String getName() {
      return m_name;
    }
   
    public void   setID(String id) {
      m_id = id;
    }
   
    public String getID() {
      return m_id;
    }
   
    public String toString() {
      return m_name;
    }
}
tbarrawiAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
You could use this convenience method:


public JTable resultSetToTable(JTable table, ResultSet rs) {
      try {
            // The below just for searches
            ResultSetMetaData metaData = rs.getMetaData();
            int numberOfColumns = metaData.getColumnCount();
            Vector columnNames = new Vector();
            // Get the column names
            for (int column = 0; column < numberOfColumns; column++) {
                  columnNames.addElement(metaData.getColumnLabel(column + 1));
            }
            // Get all rows.
            Vector rows = new Vector();
            while (rs.next()) {
                  Vector newRow = new Vector();
                  for (int i = 1; i <= numberOfColumns; i++) {
                        newRow.addElement(rs.getObject(i));
                  }
                  rows.addElement(newRow);
            }
            return new JTable(rows, columnNames);
      }
      catch (Exception e) {
            e.printStackTrace();
            return null;
      }
}
0
 
CEHJCommented:
Pass the result set to that method. The first param to that method is redundant so you can get rid of it
0
 
tbarrawiAuthor Commented:
CEHJ, but if the record set will return id,first_name,last_name, this means the JTable will have three columns visible. I don't wanna show the id?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
CEHJCommented:
Wait a minute, this is ringing a bell! Haven't we been through this before and you found a solution based on a JList?
0
 
objectsConnect With a Mentor Commented:
main thing you need to do is to create your own table model, and a class to store the details of the data (MyObject)  loaded from the database. Your table model would then look something like:

public class MyTableModel extends Abstract TableModel
{
   private static final String[] COLUMNS = { "First Name", "Last Name" };
   private List rows;

   public MyTableModel(List rows)
   {
      this.rows = rows;
   }

   public MyObject getObjectAtRow(int row)
   {
      return (MyObject) rows.get(row);
   }

   public int getRowCount()
   {
      return rows.size();
   }

   public int getColumnCount()
   {
      return COLUMNS.length;
   }

   public String getColumnName(int column)
   {
      return COLUMNS[column];
   }

   public Object getValueAt(int row, int column)
   {
      Object result = null;
      MyObject o = (MyObject) rows.get(row);
      switch (column)
      {
         case 0: result = o.getFirstName(); break;

         case 1: result = o.getLastName(); break;
      }
      return result;
    }
}
 

MyObject would look just like PairElement above but would have methods to return first and last name
0
 
objectsCommented:
You'd use the following to create your list which can then be use to create your table model

public List readResultSet(ResultSet rs)
{
     List rows = new ArrayList();
     while (rs.next())
     {
         MyObject o = new MyObject(rs.getString(1), rs.getString(1), rs.getString(2));
         rows.add(o);
     }
     return rows;
}
0
 
objectsCommented:
> this means the JTable will have three columns visible.

It sure would, the approach I suggested avoids that.
0
 
tbarrawiAuthor Commented:
CEHJ, good memory :) the first time i had one column only so JList was a good solution
0
 
CEHJCommented:
Use the code i gave you, passing the ResultSet got from your query, then do:


table.removeColumn(table.getColumnModel().getColumn(0));

The data will still be there in the table model
   
0
 
tbarrawiAuthor Commented:
CEHJ, and on row click even I will be able to retrieve the ID eventhough the column was removed??

objects, thanks, I am reading the code to understand it.
0
 
objectsCommented:
> I am reading the code to understand it.

You'll find it to be a far more flexible approach :)
And no need to go removing columns from your table ;)
0
 
CEHJCommented:
>>CEHJ, and on row click even I will be able to retrieve the ID eventhough the column was removed??

Yes. You get the value from the table model col 0, row click index
0
 
tbarrawiAuthor Commented:
what a competion! what shall I do now.... :)
0
 
objectsCommented:
I know which I'd use ;)
0
 
tbarrawiAuthor Commented:
lol i am sure you know objects

look guys since I learned two good approaches from your answers, I will split. And i will keep which approach i will use to myself :)  Thanks!
0
 
CEHJCommented:
:-)
0
 
objectsCommented:
Thanks mate, let me know if you have any more questions.
0
All Courses

From novice to tech pro — start learning today.