简体   繁体   中英

I can't convert int to string in Vaadin

I have a small problem with Vaadin and Spring Boot. When I want to change convert int to string I get this error. I know it's probably a trivial problem but I'm just starting to learn Spring Boot.

com.vaadin.flow.component.textfield.IntegerField@1c7a3814

@Route("main")
public class vaadinapp extends VerticalLayout {
  public vaadinapp() {
    IntegerField integerField = new IntegerField("Age");
    Button buttonName = new Button("Left", new Icon(VaadinIcon.ACADEMY_CAP));
    Label labelName = new Label();

    String integerFieldStr = integerField.toString();

    buttonName.addClickListener(clickEvent -> {
      labelName.setText(integerFieldStr);
    });

    add(integerField, buttonName, labelName);
  }
}

Invoking the toString method of the integerField object will return you string representation of the object, not the value, stored in it. To retrieve the value you could use the getValue method instead. Like this:

public vaadinapp() {
    IntegerField integerField = new IntegerField("Age");
    Button buttonName = new Button("Left", new Icon(VaadinIcon.ACADEMY_CAP));
    Label labelName = new Label();

    buttonName.addClickListener(clickEvent -> {
        String integerFieldStr = 
            Optional.ofNullable(integerField.getValue()) //you need this check since getValue could return null
           .map(String::valueOf)
           .orElse("");
        labelName.setText(integerFieldStr);
    });

    add(integerField, buttonName, labelName);
}

UPD: I'd also moved the value retrieval code into the listener. Thanks Eric for this point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM