【问题标题】:How to strikethrough selected text in JTextPane? (java)如何在 JTextPane 中删除选定的文本? (爪哇)
【发布时间】:2014-05-02 01:08:53
【问题描述】:

标题说明了一切。假设我有一个带有“删除所选文本”选项的右键菜单。当我在 jtextpane 中选择了一些文本时,右键单击 --> "Strikethrough selected text" ,所选文本会被删除。

有什么想法吗?

【问题讨论】:

标签: java swing jtextpane strikethrough


【解决方案1】:

Swing 文本组件使用Actions 提供文本窗格的各种格式设置功能。

以下是StyledEditorKitUnderlineAction 的代码。

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 方法来创建自己的“StrikeThroughAction”,以使用“删除线”StyleConstants 方法。

一旦您创建了一个动作,您就可以通过使用该动作创建一个 JMenuItem 或 JButton 来使用该动作。单击组件时,删除线属性将添加到选定的文本中。

【讨论】:

  • 非常感谢您的回答!这是我想要达到的 99% 的结果。正如您在上面给我的代码 cmets 所说,动作 Toggles 下划线属性。我想使用它的方式是:选择一些文本然后右键单击->删除线。选定的文本被删除,我可以继续输入普通文本(没有删除线)。
  • 编辑: 我忘了说:我不想将它用作单个操作(使用右键单击菜单选项来切换它),而是要使用它用其他方法(在那里做更多的事情)。
【解决方案2】:

在您的右键单击操作中

objJTextPane.setContentType( "text/html" );
String[] args = objJTextPane.getText().split(objJTextPane.getSelectedText());
objJTextPane.setText("<strike>" + objJTextPane.getSelectedText() + "</strike>"+ args[1].toString());

在拆分字符串时应用您的逻辑。

【讨论】:

  • 我没有使用 html 标签。
猜你喜欢
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多