FieldSelection extends Selection { public void replaceWithReferenceField(ReferenceField field, ReferenceField.DisplayType type) { int leftLength = textSelection.getText().length(); int index = textSelection.getIndex(); prepareSpanContainer(leftLength, index); field.appendReferenceTo(spanContainer, type); textSelection.mMatchedText = field.getOdfElement().getTextContent(); int textLength = textSelection.mMatchedText.length(); int offset = textLength - leftLength; SelectionManager.refresh(textSelection.getContainerElement(), offset, index + textLength); } FieldSelection(TextSelection selection); Field replaceWithSimpleField(Field.FieldType fieldType); void replaceWithReferenceField(ReferenceField field, ReferenceField.DisplayType type); void replaceWithVariableField(VariableField field); ConditionField replaceWithConditionField(String condition, String trueText, String falseText); ConditionField replaceWithHiddenTextField(String condition, String text); void applyStyle(OdfStyleBase style); @Override void cut(); void replaceWith(String newText); @Override void pasteAtEndOf(Selection positionItem); @Override void pasteAtFrontOf(Selection positionItem);  }
@Test public void testReplaceWithReferenceField() { try { search = new TextNavigation("ReplaceReferenceTarget", doc); TextSpanElement newTextSpanElement = doc.newParagraph("Selection Reference Content:").newTextSpanElement(); newTextSpanElement.setTextContent("This is a test selection reference content."); ReferenceField referenceField = Fields.createReferenceField(newTextSpanElement, "selection-test-ref"); OdfContentDom contentDom = doc.getContentDom(); NodeList nodeList = contentDom.getElementsByTagName(TextReferenceRefElement.ELEMENT_NAME.getQName()); int i = nodeList.getLength(); OdfStylesDom styleDom = doc.getStylesDom(); nodeList = styleDom.getElementsByTagName(TextReferenceRefElement.ELEMENT_NAME.getQName()); i += nodeList.getLength(); while (search.hasNext()) { TextSelection item = (TextSelection) search.nextSelection(); FieldSelection fieldSelection = new FieldSelection(item); fieldSelection.replaceWithReferenceField(referenceField, DisplayType.TEXT); i++; } nodeList = contentDom.getElementsByTagName(TextReferenceRefElement.ELEMENT_NAME.getQName()); int j = nodeList.getLength(); nodeList = styleDom.getElementsByTagName(TextReferenceRefElement.ELEMENT_NAME.getQName()); j += nodeList.getLength(); Assert.assertEquals(j, i); doc.save(ResourceUtilities.newTestOutputFile(SAVE_FILE_REPLACE)); } catch (Exception e) { Logger.getLogger(FieldSelectionTest.class.getName()).log(Level.SEVERE, e.getMessage(), e); Assert.fail("Failed with " + e.getClass().getName() + ": '" + e.getMessage() + "'"); } }