-2

I am creating a list from which the user can select from using Vaadin8. I want to get the values from the Enum but the string values with spaces not the Element Names.

public enum CustomerStatus {
    
    ImportedLead {
        public String toString() {
            return "Imported Lead";
        }
    }, 
     NotContacted{
        public String toString() {
            return "Not Contacted";
        }
    }, 
     Contacted{
        public String toString() {
            return "Contacted";
        }
    }, 
     Customer{
        public String toString() {
            return "Customer";
        }
    }, 
     ClosedLost{
        public String toString() {
            return "Closed Lost";
        }
    }
}

Here is the list created to select from the Enum elements:

private NativeSelect <CustomerStatus> status = new NativeSelect<>("Status");

And here are 3 lines I tried that did not work:

status.setItems(CustomerStatus.values().toString());

//
status.setItems(CustomerStatus.valueOf(CustomerStatus.values())); 
//
status.setItems(CustomerStatus.ClosedLost.toString(), CustomerStatus.Contacted.toString() , CustomerStatus.Customer, CustomerStatus.NotContacted, CustomerStatus.ImportedLead);
//
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

1

You can add a value property:

  public enum CustomerStatus {

  ImportedLead("Imported Lead"),
  NotContacted("Not Contacted"),
  Contacted("Contacted"),
  Customer("Customer"),
  ClosedLost("Closed Lost");

  private final String value;

  CustomerStatus(String value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return this.value;
  }

  public static CustomerStatus fromValue(String value) {
    CustomerStatus result = null;
    switch(value) {
      case "Imported Lead":
      result = CustomerStatus.ImportedLead;
      break;
      case "Not Contacted":
      result = CustomerStatus.NotContacted;
      break;
      case "Contacted":
      result = CustomerStatus.Contacted;
      break;
      case "Customer":
      result = CustomerStatus.Customer;
      break;
      case "Closed Lost":
      result = CustomerStatus.ClosedLost;
      break;
    }
    if (result == null) {
      throw new IllegalArgumentException("Provided value is not valid!");
    }
    return result;
  }
}

Usage:

status.setItems(Arrays.asList(CustomerStatus.values()));
Rafael Guillen
  • 1,343
  • 10
  • 25
-1

You could give your enum the following:

            @Override
            public String toString() {
                String result = super.toString();
                return result.replaceAll("([A-Z][a-z]+)([A-Z][a-z]+)", "$1 $2");
            }
g00se
  • 3,207
  • 2
  • 5
  • 9
  • OP has already implemented the `toString()` method on each enum value; this doesn't change what they already have. – Andy Turner Sep 09 '21 at 12:42
  • Maybe I wasn't clear enough: only *one* override is necessary. It's not necessary to repeat the method. – g00se Sep 09 '21 at 13:02