Search code examples
javaswingjtableactionlistenerjcombobox

Populate JComboBox from JTable


I have the following JComboBox:

JComboBox cbxUf;

And the following JTable

JTable tblObjetos;

which has the following structure:

------------------------
| Nome       | UF      |
------------------------
| Nome 1     | AC      |
| Nome 2     | AC      |
| Nome 3     | PE      |
------------------------

I need to pass the selected row from tblObjetos to cbxUf's selectedItem, so I added a MouseListener to tblObjetos containing the following event:

public void mouseClicked(MouseEvent evt){
    int col = tblObjetos.getSelectedColumn();
    int row = tblObjetos.getSelectedRow();
    cbxUf.setSelectedItem(tblObjetos.getModel().getValueAt(row, col));
}

It manages to populate the cbxUf with the selected row but ONLY if I click on the UF column. If I click on the left side of the table, the selectedItem doesn't change at all.

Am I doing something wrong? Are there any alternatives to this?

Thanks!


Solution

  • cbxUf.setSelectedItem(tblObjetos.getModel().getValueAt(row, col));
    

    My guess is that your comboBox only contains values for the second column so there is no object to select when you click on the first column. For example if you click on the first row you try to set the selected item to be "Nome 1". This value does not exist in your combo box so the selection is not changed. What you really want is to select "AC".

    Your code should be:

    cbxUf.setSelectedItem(tblObjetos.getModel().getValueAt(row, 1));
    

    Also, nstead of using a MouseListener add a ListSelectionListener to the tables selection model.