JTextPane中如何让光标紧邻位置的样式自动应用到新输入文本
问题根因
你目前只修改了切换按钮的选中状态,没有同步更新JTextPane的输入属性集:Swing中JTextPane后续输入的文本样式默认取自getInputAttributes()返回的属性集合,和按钮是否选中没有直接关联。同时你之前调用动作的方式参数错误,无法正确作用到当前文本框。
修复方案
直接修改CaretListener中的逻辑,检测到光标左右的样式后,同步更新输入属性集,同时补充边界判断避免光标在最左侧时数组越界:
tp.addCaretListener((CaretEvent ce) -> { int caretPosition = tp.getCaretPosition(); if(caretPosition != lastCaretPosition) { lastCaretPosition = caretPosition; StyledDocument doc = tp.getStyledDocument(); MutableAttributeSet inputAttr = tp.getInputAttributes(); // 边界处理:光标在最左侧时无前序字符 AttributeSet asPrev = null; if (caretPosition > 0) { Element charElementPrev = doc.getCharacterElement(caretPosition - 1); asPrev = charElementPrev.getAttributes(); } Element charElementAfter = doc.getCharacterElement(caretPosition); AttributeSet asAfter = charElementAfter.getAttributes(); // 处理粗体 boolean shouldBeBold = (asPrev != null && StyleConstants.isBold(asPrev)) || StyleConstants.isBold(asAfter); StyleConstants.setBold(inputAttr, shouldBeBold); boldButton.setSelected(shouldBeBold); // 处理下划线 boolean shouldBeUl = (asPrev != null && StyleConstants.isUnderline(asPrev)) || StyleConstants.isUnderline(asAfter); StyleConstants.setUnderline(inputAttr, shouldBeUl); ulButton.setSelected(shouldBeUl); // 处理斜体 boolean shouldBeItalic = (asPrev != null && StyleConstants.isItalic(asPrev)) || StyleConstants.isItalic(asAfter); StyleConstants.setItalic(inputAttr, shouldBeItalic); itButton.setSelected(shouldBeItalic); } });
原有尝试失败的原因
- 直接调用
new StyledEditorKit.BoldAction().actionPerformed(null)时,Action无法获取当前的JTextPane作为事件源,不会作用到目标文本框 - 调用
setCharacterAttributes修改现有字符的属性,而非输入默认属性,会误改已有文本的格式,导致内容异常 - 调用
boldButton.doClick()无效是因为你设置了按钮focusable=false,触发的Action事件源是按钮而非当前文本框,无法正确更新文本框的输入属性
内容的提问来源于stack exchange,提问作者Jeremy Wilson
相关产品推荐
相关产品推荐

