gpt4 book ai didi

java - 将JComboBox添加到JTable : ComboBoxes in different rows are not independent

转载 作者:行者123 更新时间:2023-12-02 12:51:43 25 4
gpt4 key购买 nike

我有一个带有组合框的表格,用户可以在其中选择一个国家/地区。我有问题,每行中的组合框不是彼此独立的。当我选择 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;
}

}

最佳答案

您使用 JCombobox 作为渲染器,请尝试使用编辑器...

参见this example来自甲骨文。

关于java - 将JComboBox添加到JTable : ComboBoxes in different rows are not independent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44582969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com