Question

I have a JTextPane for users to write journal entries which they can style by selecting text and choosing a menu item such as bold or italic etc. These items are connected to one of the Styled Editor kits (eg StyledEditorKit.BoldAction() ).

Is there any way of detecting whether text at a given document position has been styled with one of these kits? And if so how?

       //Create the style menu.
protected JMenu createStyleMenu() {
    JMenu menu = new JMenu("Style");

    Action action = new StyledEditorKit.BoldAction();  
    action.putValue(Action.NAME, "Bold");        
    menu.add(action);

    action = new StyledEditorKit.ItalicAction();
    action.putValue(Action.NAME, "Italic");
    menu.add(action);

    action = new StyledEditorKit.UnderlineAction();
    action.putValue(Action.NAME, "Underline");
    menu.add(action);

    menu.addSeparator();

    menu.add(new StyledEditorKit.FontSizeAction("12", 12));
    menu.add(new StyledEditorKit.FontSizeAction("14", 14));
    menu.add(new StyledEditorKit.FontSizeAction("18", 18));
    menu.add(new StyledEditorKit.FontSizeAction("36", 36));

    menu.addSeparator();

    menu.add(new StyledEditorKit.FontFamilyAction("Serif",
                                                  "Serif"));
    menu.add(new StyledEditorKit.FontFamilyAction("SansSerif",
                                                  "SansSerif"));

    menu.addSeparator();

    menu.add(new StyledEditorKit.ForegroundAction("Red",
                                                  Color.red));
    menu.add(new StyledEditorKit.ForegroundAction("Green",
                                                  Color.green));
    menu.add(new StyledEditorKit.ForegroundAction("Blue",
                                                  Color.blue));
    menu.add(new StyledEditorKit.ForegroundAction("Black",
                                                  Color.black));

    return menu;
}

Any help would be much appreciated. Thank you.

Was it helpful?

Solution

You can query the attributes of a certain character of your document:

StyledDocument doc = (StyledDocument)textPane.getDocument();
Element element = doc.getCharacterElement(position);

Boolean isItalic = element.getAttributes().getAttribute(StyleConstants.Italic);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top