void (@NotNull String textToSet, JTextComponent component) { String existingText = component.getText(); if (!existingText.equals(textToSet)) { component.setText(textToSet); // textToSet should be selected even if we have no selection before (if we have the selection then setText will remain it) if (component.getSelectionStart() == component.getSelectionEnd()) component.selectAll(); } }