2017-06-16 58 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