Java.lang.String cannot be cast to error , when capturing data in Jcomobox to save

Asked

Viewed 4,866 times

1

inserir a descrição da imagem aqui

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

  • cbNomeUsuario - It’s Jcomobox’s name that they’re picking up a List Functio .

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

A cast error, someone can help me ?

I want to take the return or is the employee ID to store in the bank.

Save to normal bank : getFunctioning(). getId();

  • If you show your class Funcionário makes it easier to help you.

2 answers

1

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

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

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

1

I didn’t see the declaration and initialization of your Combobox but the class JComboBox is parameterized. Soon you can declare something like: JComboBox<Funcionario> combo = new JComboBox<Funcionario>(); or JComboBox<Funcionario> combo = new JComboBox<>();

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

If you can’t change that, you can use the method getSelectedIndex() and access the object of your collection.

And just like Piovezan said, you’re performing a cast of Funcionario on an object of the type String. Which generates the detected error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.