I have a Requirement where I got a JTable Column defaulting with certain data on Load. Now , I need a combobox on the same Column with that default value already selected in the combobox of that column in the Table +few other options to select or change the value of the cell of that column.
Asked
Active
Viewed 1,679 times
0
-
1See [`TableComboBoxByRow`](http://stackoverflow.com/a/3256602/230513). – trashgod Aug 27 '13 at 11:04
2 Answers
0
Here is the Sample Code:
public class Test extends JFrame {
public void init() {
JTable table = new JTable( new Object[][] { { "Paul J" , "20" }, { "Jerry M" , "30" }, { "Simon K" , "25" } },
new String[] { "Name" , "Age" } );
table.getColumnModel().getColumn(1).setCellEditor( new SampleCellEditor() );
getContentPane().add( new JScrollPane( table ));
setSize( 400, 200 );
setVisible(true);
}
// Sample Editor to Show Combobox with all sample values in that column
// also can edit the value to add new Value that is not in the column
public static class SampleCellEditor extends DefaultCellEditor {
public SampleCellEditor( ) {
super( new JComboBox() );
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int column) {
JComboBox combo = ( JComboBox ) editorComponent;
combo.setEditable(true); // make editable so that we can add new values
combo.removeAllItems(); // remove All pre-existing values.
Vector<Object> objectList = new Vector<Object>();
Object obj = null;
for( int i = 0; i < table.getRowCount(); i++ ) {
obj = table.getValueAt( i, column );
if( !objectList.contains( obj ) )
objectList.add( obj );
}
combo.setModel( new DefaultComboBoxModel(objectList) );
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t = new Test();
t.init();
}
}
I hope this will solve your problem.

Gnanasekaran Palanisamy
- 887
- 5
- 7
0
Let me Explain clearly with the above Example.
JTable table = new JTable( new Object[][] { { "Paul J" , "20" }, { "Jerry M" , "30" }, { "Simon K" , "25" } }, new String[] { "Name" , "Age" } );
The above is the data that is going to be loaded in the Table Initially. Where the Columns as Name and Age and values resp.
Now,I need is ' Age ' column will a combobox and For 'Paul J' in the Table populates the 'Age' as 20 by default and the comboBox should appear in this column and the User Now wants to change, the User now will have a option to select another value from the combobox to overwrite the default value.

user2721206
- 1
- 1