简体   繁体   中英

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. When I have selected some text in jtextpane, right-click --> "Strikethrough selected text" , and the selected text gets strikedthrough.

Any ideas?

Swing text components use Actions to provide the various formatting features of a text pane.

Following is the code for the UnderlineAction of the StyledEditorKit .

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.

Once you create a Action you can then use the Action by creating a JMenuItem or JButton with the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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