JComboBox in table. Use like <OPTION> in html
I have such pretty difficult question:
I am trying to let user work with DB through JTable.
The problem is:
For example, I have table in my DB:
Table Department:
ID (key field, int, auto_inc);
Dep(char(50));//name of department
It looks like:
1Science researches department
2Financial department
3Direction
4Analysis department
Table Person:
ID (key field, int, auto_inc);
Family (char 50);//family of person
Name (char 50);//name of person
DepartmentID (unsigned int)//keeps ID of department to which person belongs
It looks like:
1Paterson--Jimm--1
2SmithRobert-3
3Spears-Jack-2
4Winston--James-4
5ArtuaKristie--1
When Ioutput table Person to JTable, I want to let userchoose from combobox Department of person.
Of course, if I would give him just ID of deparments卼hat抯 foolish thing.
1.So, I know how to set ComboBox to JTable.
2.Also I have Vector with query results.
This vector keeps ID of department and name of Department.
3.I抳e already loaded this vector to ComboBox, set Combobox as default cell render, but, ofcourse I can抰 use methods setValueAt() and getValueAt();
So I have to show to user name of department, but keep in mind ID corresponding to it.
And when setValueAt()/getValueAt() methods used I have to work with ID, not with the name of Department.
(I mean to update ID in DB table )
I solved such tasks in html+php.
<OPTION> has to fields:value andcaption. So It was pretty easy to show caption to user and make operations with ID, kept in value field.
Is it possible to do the same with JComboBox in Java?
publicvoid setupDepartmentComboBox(JTable table, TableColumn SheetTypeIDcolumn,Connection con){
Connection connection=con;
Statement statement =null;
Vector stID =new Vector();
try{
statement=connection.createStatement();
}
catch (Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
}
String query="SELECT ID,Department FROM Department";
if(connection==null || statement ==null){
//bla-bla-bla
}
try{
int i;
ResultSet resultSet;
ResultSetMetaData metaData;
resultSet = statement.executeQuery(query);
//get num of columns in table/***/getColumnCount()
//get names of columns /***/getColumnLabel(i+1)
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
String[] columnNames =new String[numberOfColumns];
for(i=0;i<numberOfColumns;i++){
columnNames[i]= metaData.getColumnLabel(i+1);
}//for
while (resultSet.next()){
Vector newRow =new Vector();
for (i=1; i><= numberOfColumns;i++){
newRow.addElement(resultSet.getObject(i));
}//for
stID.addElement(newRow);
}//while
}//try
catch(SQLException ex){
//bla-bla-bla
}
JComboBox combobox =new JComboBox((Vector<?>)stID);
SheetTypeIDcolumn.setCellEditor(new DefaultCellEditor(combobox));
DefaultTableCellRenderer renderer =new DefaultTableCellRenderer();
SheetTypeIDcolumn.setCellRenderer(renderer);
}//setupSheetTypeIDComboBox

