标题说明了一切。假设我有一个带有“删除选定文本”选项的右键菜单。当我在 jtextpane 中选择一些文本时,右键单击 --> "删除选定的文本",选定的文本将被删除。
有什么想法吗?
最佳答案
Swing 文本组件使用 Actions
提供文本 Pane 的各种格式设置功能。</p>
以下是 StyledEditorKit
的 UnderlineAction
的代码。
public static class UnderlineAction extends StyledTextAction {
/**
* Constructs a new UnderlineAction.
*/
public UnderlineAction() {
super("font-underline");
}
/**
* Toggles the Underline attribute.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setUnderline(sas, underline);
setCharacterAttributes(editor, sas, false);
}
}
}
所以基本上,您需要通过替换“下划线”StyleConstants 方法来使用“删除线”StyleConstants 方法来创建自己的“StrikeThroughAction”。
创建操作后,您可以通过使用该操作创建 JMenuItem 或 JButton 来使用该操作。单击该组件时,删除线属性将添加到所选文本中。
关于java - 如何在 JTextPane 中删除选定的文本? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419238/