?
Solved

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

Posted on 2005-03-11
17
Medium Priority
?
281 Views
Last Modified: 2008-03-06
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;
    }
}
0
Comment
Question by:tbarrawi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 5
17 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 1000 total points
ID: 13521503
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 13521520
Pass the result set to that method. The first param to that method is redundant so you can get rid of it
0
 

Author Comment

by:tbarrawi
ID: 13521579
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 13521605
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
 
LVL 92

Assisted Solution

by:objects
objects earned 1000 total points
ID: 13521615
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
 
LVL 92

Expert Comment

by:objects
ID: 13521628
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
 
LVL 92

Expert Comment

by:objects
ID: 13521630
> this means the JTable will have three columns visible.

It sure would, the approach I suggested avoids that.
0
 

Author Comment

by:tbarrawi
ID: 13521641
CEHJ, good memory :) the first time i had one column only so JList was a good solution
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13521652
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
 

Author Comment

by:tbarrawi
ID: 13521678
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
 
LVL 92

Expert Comment

by:objects
ID: 13521727
> 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
 
LVL 86

Expert Comment

by:CEHJ
ID: 13521759
>>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
 

Author Comment

by:tbarrawi
ID: 13521795
what a competion! what shall I do now.... :)
0
 
LVL 92

Expert Comment

by:objects
ID: 13521805
I know which I'd use ;)
0
 

Author Comment

by:tbarrawi
ID: 13521830
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 13521851
:-)
0
 
LVL 92

Expert Comment

by:objects
ID: 13521862
Thanks mate, let me know if you have any more questions.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month13 days, 19 hours left to enroll

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question