gpt4 book ai didi

java - 如何停止将已添加的值从 JCombobox 添加到 JTable

转载 作者:行者123 更新时间:2023-11-30 03:10:19 24 4
gpt4 key购买 nike

我正在研究 netbeans 并创建一个 swing 应用程序。我创建了一个 JComboBox 和一个 JTable。我可以通过单击按钮将值从 JComboBox 添加到 JTable,但如果我重复相同的过程,相同的值会再次添加到表中。如何停止添加JComboBox已有的值。

这是JComboBox的代码

private void populateCombo(){
organizationComboBox.removeAllItems();
for (Organization.Type type : Organization.Type.values()){
organizationComboBox.addItem(type);
}
}

这是JTable的代码

private void populateTable(){
DefaultTableModel model = (DefaultTableModel) organizationTable.getModel();
model.setRowCount(0);

for (Organization organization : organizationDirectory.getOrganizationList()){
Object[] row = new Object[2];
row[0] = organization.getOrganizationID();
row[1] = organization.getName();

model.addRow(row);
}
}

这是我的添加按钮的代码

Type type = (Type) organizationComboBox.getSelectedItem();
Organization o = organizationDirectory.createOrganization(type);

if(type.equals(Type.Receptionist)){
o.getSupportedRole().add(new ReceptionistRole());
}else
if(type.equals(Type.Doctor)){
o.getSupportedRole().add(new DoctorRole());
}else
if(type.equals(Type.VaccineManager)){
o.getSupportedRole().add(new VaccineManagerRole());
}else
if(type.equals(Type.LabAssistant)){
o.getSupportedRole().add(new LabAssistantRole());
}else
if(type.equals(Type.Donor)){
o.getSupportedRole().add(new DonorRole());
}else
if(type.equals(Type.Patient)){
o.getSupportedRole().add(new PatientRole());
}

populateTable();

提前致谢。

最佳答案

不要使用DefaultTableModel。此类仅适用于简单案例和演示应用程序。简单看一下here例如您自己的模型。

所以你的模型看起来像:

public class OrganizationModel extends AbstractTableModel {
protected String[] columnNames;
protected List<Organization> dataVector;

public OrganizationModel(String[] columnNames) {
this.columnNames = columnNames;
dataVector = new ArrayList<Organization>();
}

public String getColumnName(int column) {
return columnNames[column];
}

public boolean isCellEditable(int row, int column) {
return false;
}

public Class getColumnClass(int column) {
return String.class;
}

public Object getValueAt(int row, int column) {
return column == 0? dataVector.get(row).getOrganizationID() : dataVector.get(row).getName();
}

public void addRowWhenNotExist(Organization o) {
if (!dataVector.contains(o)) {
dataVector.add(o);
fireTableRowsInserted(dataVector.size() - 1, dataVector.size() - 1);
}
}
}

为了正确运行此示例,您还需要为您的组织类正确定义方法 equals 和 hashCode。

public class Organization {

// your stuff

public boolean equals(Object another) {
if (another instanceof Organization) {
return getOrganizationID() == ((Organization) another).getOrganizationID();
} else {
return false;
}
}

public int hashCode() {
return getOrganizationID();
}
}

关于java - 如何停止将已添加的值从 JCombobox 添加到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751577/

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