0

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?

2 Answers2

1

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.

camickr
  • 308,339
  • 18
  • 152
  • 272
  • Thanks a lot for your answer! That's 99% the result I want to achieve. As the code comments you gave me above says, the action **Toggles** the underline attribute. The way I want to use it is: Select some text then right click--> strikethrough. The selected text gets strikedthrough and I can keep typing normal text(no strikethrough). –  May 02 '14 at 12:42
  • **Edit:** I forgot to mention: I don't want to use it as a single action(using a right click menu option to toggle it), but to use it in some other method(doing more stuff in there). –  May 02 '14 at 12:58
0

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.

Abin
  • 540
  • 4
  • 15