如何通过JTable中的JComboBox获取Selected Value

时间:2013-07-30 21:02:45

标签: java swing jtable

我创建了一个带有JComboBox CellEditor列的JTable。这很好。 但是,当我尝试通过组合框检索所选值时,我只获取鼠标在特定行中选择的值。我似乎无法按行获取所选值。 这是我的代码:

  addressList = new ArrayList<>(); 
    for(int currentRow = 0; currentRow < editAddressFrm.getAddressTable().getRowCount(); currentRow++)
    {

            //ADDRESS
    offenderAddress = new MyAddress();


    DefaultCellEditor ownerEditor = (DefaultCellEditor) editAddressFrm.getAddressTable().getCellEditor(currentRow, 1);       
    JComboBox ownerCb =(JComboBox) ownerEditor.getComponent();
    ListItem selectedItem =(ListItem) ownerCb.getSelectedItem();  //HERE IS WHERE I HAVE THE PROBLEM.I AM NOT GETTING THE VALUE FOR THE SPECIFIC ROW

    offenderAddress.setOwnerCode(selectedItem.getID());

    offenderAddress.setLine1(
            editAddressFrm.getAddressTable().getModel().getValueAt(currentRow, 2).toString() 
            );

    offenderAddress.setLine2(
            editAddressFrm.getAddressTable().getModel().getValueAt(currentRow, 3).toString() );

    offenderAddress.setCity(
            editAddressFrm.getAddressTable().getModel().getValueAt(currentRow, 4).toString() );
    offenderAddress.setProvince(
            editAddressFrm.getAddressTable().getModel().getValueAt(currentRow, 5).toString() );
    offenderAddress.setPostalZone(
            editAddressFrm.getAddressTable().getModel().getValueAt(currentRow, 6).toString() );
    }

1 个答案:

答案 0 :(得分:5)

comboBox仅用于编辑单元格。它不包含单元格的数据。

您需要从表格中获取使用以下内容的数据:

table.getValueAt(...);

table.getModel().getValueAt(...);

取决于您的具体要求

如果您仍在编辑单元格,则数据可能尚未保存到模型中。要解决此问题,请参阅:Table Stop Editing