我有一个带有组合框的桌子,用户可以选择一个国家。我有问题,每行中的组合框不是彼此独立的。当我在行A中选择一个项目然后单击行B中的组合框时,组合框B将自动设置为与组合框A相同的值。
代码:
DefaultTableModel model = new DefaultTableModel();
//Creating the Headers
ArrayList<Adress> adressList = customer.getAdressList();
//customer.getAdressList() is an ArrayList, which has been populated from SQL
model.addColumn("ID");
model.addColumn("Country");
//Iterate through Adresses of current Customer and fill JTable
for(Iterator<Adress> iterator = adressList.iterator(); iterator.hasNext();){
Adress adress = iterator.next();
Object[] data = new Object[2];
data[0] = adress.getID();
data[1] = adress.getCountry();
model.addRow(data);
}
//Populate combobox with values from an enum
JComboBox country_comboBox = new JComboBox(CountryEnum.values());
// Set Model, Renderer and Editor
table.setModel(model);
table.getColumnModel().getColumn(1).setCellRenderer(new JComboBoxCountryRenderer(country_comboBox));
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(country_comboBox));
和渲染器:
public class JComboBoxCountryRenderer extends JComboBox implements TableCellRenderer{
CountryEnum country;
public JComboBoxCountryRenderer(JComboBox comboBox) {
if (comboBox != null) {
this.setModel(comboBox.getModel());
this.setSelectedIndex(comboBox.getSelectedIndex());
}
}
@Override
public Component getTableCellRendererComponent(JTable arg0, Object value, boolean arg2, boolean arg3, int arg4,
int arg5) {
if (value instanceof CountryEnum) {
this.setSelectedItem((CountryEnum) value);
}
return this;
}
}