Tuesday, April 14, 2009

JAVA Table with Combobox control

In java swing we can add Controls in table.

Here we are going to add Combobox in a table control.

Before going to create a table instance, we have to create table headers and data with empty strings like below

final String[] colheads={"S.No","Item ID","Qty",Rate","Amount" };
final Object[][] data={
{1,"","","",""},
{2,"","","",""},
{3,"","","",""},
{4,"","","",""},
{5,"","","",""},
};
Now we create a table and add scroll panes to it...

JTable table=new JTable(data,colheads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(table,v,h);

Note: add this table into panel to show...

Then to add combo box in the run time, we add code in focus gained event of table like below..

public void focusGained(FocusEvent e)
{
TableColumn tc=table.getColumnModel().getColumn(1);
JComboBox dw=new JComboBox();

dw.addItem("Select");
dw.addItem("IN1");
dw.addItem("IN2");
dw.addItem("IN3");
dw.addItem("IN4");

tc.setCellEditor(new DefaultCellEditor(dw));
}

Note: we have to add focus listener to table and after that add code for it..in the focus gained method we have to add above code..


In the output,It will show a table.. when you access table you can able select item values at column 2...


Thank you

No comments:

Post a Comment