How to show in JOptionPane, a tribute of an enum

0

I'm using enums and JOptioPane, and I want to show the enum attribute, (I mean a string), this is what I have:

public Cities readCityOrigen() {
    Cities [] listCityOrigen = Cities.values();
    Cities city = (Cities) JOptionPane.showInputDialog(null, 
            "Seleccione la ciudad de origen del vuelo",
            "CIUDAD DE ORIGEN", JOptionPane.QUESTION_MESSAGE, 
            null, listCityOrigen, listCityOrigen[0]);
        return city;
}'

package models;

 public enum Cities {
  BOGOTA ("Bogota"),
  CALI ("Cali"),
  BUCARAMNAGA ("Bucaramanga"),
  CARTAGENA("Cartagena"),
  SANTA_MARTA("Santa Marta"),
  MEDELLIN("Medellin"),
  TUNJA("Tunja"),
  PEREIRA("Pererira"),
  ARMENIA("Armenia"),
  RIOHACHA("Riohacha"),
  TOKYO("Tokio"),
  CARACAS("Caracas"),
  PARIS("Paris"),
  NEW_YORK("Nueva Yotk"),
  MIAMI("Maimi"),
 MADRID("Madrid");

String  cities;
Cities(String cities){
    this.cities = cities;
}
public String getCities(){
    return this.cities;
}
}

I want the string to appear in the JOptionPane, but I get the attribute literal

    
asked by Yeferson Gallo 22.10.2016 в 03:55
source

2 answers

2

A solution would be within your class Cities Implement your method toString () to return the name given to its constants

public enum Cities {
 /* el resto del código */

/* Agregar el método toString*/
@Override
public String toString() {
    return cities;
}
    
answered by 22.10.2016 в 04:19
2

I think you could put within the Cities , the toString() method, and modify the method so that it replaces all lowercase letters except the first one and replace all "_" with spaces, like this:

public enum Command {
    BOGOTA,CALI,BUCARAMNAGA,CARTAGENA,SANTA_MARTA,MEDELLIN,TUNJA,PEREIRA,ARMENIA,RI_HACHA,TOKYO,CARACAS,PARIS,NEW_YORK,MIAMI,MADRID;


@Override
public String toString() {
    //cambiamos todos los "_" por espacios en blanco y cambiamos las letras 
    //minusculas con toLowerCase y concatenamos el resto
    String name = name().replaceAll("_", " ").toLowerCase();
    //la primer letra la ponemos en mayuscula con toUpperCase
    name = name.substring(0, 1).toUpperCase() + name.substring(1);
    return name;
   }
}
    
answered by 24.10.2016 в 04:52