简体   繁体   English

如何在JTextPane中删除选定的文本? (Java)的

[英]How to strikethrough selected text in JTextPane? (java)

Title says it all. 标题说明了一切。 Let's say I have a right-click menu with "Strikethrough selected text" option. 假设我有一个带有“Strikethrough selected text”选项的右键菜单。 When I have selected some text in jtextpane, right-click --> "Strikethrough selected text" , and the selected text gets strikedthrough. 当我在jtextpane中选择了一些文本时,右键单击 - >“删除所选文本”,所选文本将被删除。

Any ideas? 有任何想法吗?

Swing text components use Actions to provide the various formatting features of a text pane. Swing文本组件使用Actions来提供文本窗格的各种格式设置功能。

Following is the code for the UnderlineAction of the StyledEditorKit . 以下是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);
        }
    }
}

So basically you will need to create your own "StrikeThroughAction" by replacing the "underline" StyleConstants methods to use the "strikethrough" StyleConstants methods. 所以基本上你需要通过替换“下划线”StyleConstants方法来创建自己的“StrikeThroughAction”来使用“删除线”StyleConstants方法。

Once you create a Action you can then use the Action by creating a JMenuItem or JButton with the Action. 创建Action之后,您可以通过使用Action创建JMenuItem或JButton来使用Action。 When the component is clicked the strike through attribute will then be added to the selected text. 单击该组件后,将通过属性添加到所选文本中。

in your right click action 在您的右键单击操作中

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

apply your logic in splitting string. 在分裂字符串中应用你的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM