Problem with adding JCombobox in JTable in Java?
I have added a combobox in a JTable, the adding code as follows:
Vector<String> header = new Vector<String>();
Vector data = new Vector();
String[] h = new String[]{"Music", "Movie", "Sport"};
header.add("Code");
header.add("Name");
header.add("Salary");
header.add("Hobby");
loadData(); // Add some data to the table
DefaultTableModel tblModel;
tblModel = (DefaultTableModel) this.tblEmp.getModel();
tblModel.setDataVector(data, header);
// Adding combobox to the last column
TableColumn hobbyColumn = tblEmp.getColumnModel().getColumn(3);
hobbyColumn.setCellEditor(new MyComboBoxEditor(h));
Things worked fine until I dynamically add a new row to the table using the code:
Ve开发者_Python百科ctor v = new Vector();
v.add("E333");
v.add("Peter");
v.add(343);
v.add(""); // This last colum is the combobox so I put it as ""
data.add(v);
tblEmp.updateUI();
Data is added to the table but the combobox in the last column cannot be selected anymore. The combobox is still displayed when I click on the row but cannot select a value. How can I handle this problem, please?
Never use the updateUI() method. Read the API to see what this method actually does. It has nothing to do with changing the data in a model.
JTable already supports a combo box editor so there is no need to create a custom MyComboBoxEditor. Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables", for a working example of using a combo box as an editor.
精彩评论