Java.lang.String error can not be cast to when capturing data in Jcomobox to save

1

I have the button event saved, when I click to save, the following appears: Java.lang.String cannot be cast to org.nomedopacote.modelo.Funcionario

  • cbNomeUsuario - This is the name of Jcomobox that is getting a List Officer.

        usuario.setFuncionario((Funcionario) cbNomeUsuario.getSelectedItem());
    

A cast error, can anyone help me?

I want to get the return or the employee ID to save to the bank.

Save to normal bank: object.getFunction (). getId ();

    
asked by anonymous 25.05.2014 / 20:38

2 answers

1

Your (Funcionario) cbNomeUsuario.getSelectedItem() call is trying to convert an object of type Funcionario to type String , which is being returned by cbNomeUsuario.getSelectedItem() . These are incompatible types.

In fact, your code suggests that you want to save an object of type Funcionario returned by a method that returns only the user name ( cbNomeUsuario.getSelectedItem() ).

Correct the getSelectedItem() method, or post the code in your question to try to understand what might be happening.

    
25.05.2014 / 20:49
1

I did not see the declaration and initialization of your ComboBox but the class JComboBox is parameterized. You can then declare something like: JComboBox<Funcionario> combo = new JComboBox<Funcionario>(); or JComboBox<Funcionario> combo = new JComboBox<>() ;

And insert items normally: combo.addItem(...); using objects of class Funcionario without needing to convert to String .

If you can not change this, you can use the getSelectedIndex() method and access the object in your collection.

And just like Piovezan said, you're casting Funcionario on an object of type String . What causes the error detected.

    
25.05.2014 / 20:51