You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TextAreaTextFieldCursorPosition.java 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.vaadin.tests.components.textarea;
  2. import com.vaadin.annotations.Widgetset;
  3. import com.vaadin.server.VaadinRequest;
  4. import com.vaadin.tests.components.AbstractTestUIWithLog;
  5. import com.vaadin.ui.AbstractTextField;
  6. import com.vaadin.ui.Button;
  7. import com.vaadin.ui.TextArea;
  8. import com.vaadin.ui.TextField;
  9. @Widgetset("com.vaadin.DefaultWidgetSet")
  10. public class TextAreaTextFieldCursorPosition extends AbstractTestUIWithLog {
  11. public static final String GET_POSITION = "getposition";
  12. public static final String INSERT = "insert";
  13. @Override
  14. protected void setup(VaadinRequest request) {
  15. TextArea textArea = new TextArea("Simple Text Area");
  16. textArea.setValue("I am just a piece of random text");
  17. textArea.setWidth("500px");
  18. addComponent(textArea);
  19. TextField textField = new TextField("Simple Text field");
  20. textField.setValue("I am just a piece of random text");
  21. textField.setWidth("500px");
  22. addComponent(textField);
  23. Button posButton = new Button("Get Position");
  24. posButton.setId(GET_POSITION);
  25. posButton.addClickListener(c -> {
  26. log("TextArea position: " + textArea.getCursorPosition());
  27. log("TextField position: " + textField.getCursorPosition());
  28. });
  29. addComponent(posButton);
  30. Button insertButton = new Button("Insert");
  31. insertButton.setId(INSERT);
  32. insertButton.addClickListener(c -> {
  33. insert(textArea);
  34. insert(textField);
  35. });
  36. addComponent(insertButton);
  37. }
  38. private void insert(AbstractTextField field) {
  39. String value = field.getValue();
  40. if (field.getCursorPosition() != -1) {
  41. int pos = field.getCursorPosition();
  42. log("Insert position: " + field.getCursorPosition());
  43. value = value.substring(0, pos) + "-insertedtext-"
  44. + value.substring(pos, value.length());
  45. } else {
  46. value += "-appendedtext";
  47. }
  48. field.setValue(value);
  49. }
  50. }