IntelliJ IDEA 插件开发:用字符变量替换选中代码并实现自动生成特效
// 获取编辑器对象 Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor == null) { return; } // 获取文档对象 Document document = editor.getDocument();
// 获取选中文本的起始和结束位置 SelectionModel selectionModel = editor.getSelectionModel(); int start = selectionModel.getSelectionStart(); int end = selectionModel.getSelectionEnd();
// 用字符变量value的值替换选中的代码 String value = 'new_value'; document.replaceString(start, end, value);
// 实现编辑框代码逐个字符自动生成的特效 // 获取当前光标位置 CaretModel caretModel = editor.getCaretModel(); int offset = caretModel.getOffset();
// 获取当前行的文本 int lineNumber = document.getLineNumber(offset); int lineStartOffset = document.getLineStartOffset(lineNumber); int lineEndOffset = document.getLineEndOffset(lineNumber); String lineText = document.getText(new TextRange(lineStartOffset, lineEndOffset));
// 逐个字符输出 for (int i = 0; i < lineText.length(); i++) { final int finalI = i; ApplicationManager.getApplication().invokeLater(() -> { // 将字符添加到编辑框 editor.getDocument().insertString(offset + finalI, String.valueOf(lineText.charAt(finalI))); // 移动光标 caretModel.moveToOffset(offset + finalI + 1); // 刷新UI editor.getContentComponent().repaint(); }, ModalityState.any()); try { // 等待一段时间再输出下一个字符,以实现特效 Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
原文地址: https://www.cveoy.top/t/topic/mVSg 著作权归作者所有。请勿转载和采集!