Search code examples
javaswingjtextpanestrikethrough

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?


Solution

  • 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.