Upload a list of Enums

0

I have selectOneMenu like this:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
 <f:selectItems itemLabel="#{naturemb.carregarAtributos()}" itemValue="#{naturemb.carregarAtributos()}" />
</p:selectOneMenu>

I want to display the values of my Enum:

package br.com.pokemax.modelo;

public enum Atributos {

    HP("HP"), ATTACK("Attack"), DEFENSE("Defense"), SPECIAL_ATTACK("Sp. Attack"), SPECIAL_DEFENSE("Sp. Defense"), SPEED(
            "Speed");

    private String nome;

    private Atributos(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

I created a method on the controller like this:

public String carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        for (int i = 0; i < lista.size(); i++) {
            return lista.get(i).getNome();
        }

        return "";
    }

But it's not working, can anyone help me?

    
asked by anonymous 18.11.2016 / 16:31

3 answers

1

Change your method to:

public List<String> carregarAtributos() {
        List<Atributos> lista = Arrays.asList(Atributos.values());
        List<String> retorno = new List<String>();
        for (int i = 0; i < lista.size(); i++) {
           retorno.add(lista.get(i).getNome());
        }
        return retorno;
}
    
18.11.2016 / 19:30
2

If you already have an Enum, you can use it without creating a String list. It is better because it facilitates reuse. In your example, just do:

public List<Atributos> carregarAtributos() {
   return Arrays.asList(Atributos.values());
}

And in selectOneMenu:

<p:selectOneMenu id="diminui" value="#{naturemb.nature.diminui}" effect="clip">
   <f:selectItems var="atributo" itemLabel="#{atributo.nome}" itemValue="#{atributo}" value="#{naturemb.carregarAtributos()}"/>
</p:selectOneMenu>

Obs. 1: as you are going to use Enum instead of the string, you have to change the type to Enum tb in the target variable.

Obs. 2: I do not think it's necessary to put a setNome in the enum because you will not be able to change the value at runtime, only at creation (in Atributos(String nome) ).

    
18.11.2016 / 22:08
1

Douglas,

The easiest way to return the list of enums is:

public EnumSet<Atributos> listarAtributos() {
    return EnumSet.allOf(Atributos.class);
}

I hope it helps;)

Hugs!

    
06.12.2016 / 20:15