Question

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?

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top