2017-06-16 74 views
0

我有一个带有组合框的表,用户可以选择一个国家。我有问题,每行中的组合框不是彼此独立的。当我在A行选择一个项目,然后点击在B行的组合框,组合框B被自动设置为相同的值,组合框A.将JComboBox添加到JTable:不同行中的组合框不是独立的

代码:

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; 
    } 

} 

回答

1

您使用JCombobox作为渲染器,请尝试使用作为一个编辑,而不是...

见从甲骨文。

+0

所以我需要实现我自己的CellEditor? – abinmorth

+0

不,只看到链接上突出显示的行... –

+0

但我已经在使用DefaultCellEditor – abinmorth