Michael Robinson
Michael Robinson

Reputation: 29498

How do I get the style of the selected text in a JTextPane?

I'm trying to create a simple WYSIWYG editor that will allow users to select text and bold/underline/italicise it. Currently the user can select text, right-click it and select bold from a popup menu, which ends up applying the bold style to the selected text like so:

this.getStyledDocument().setCharacterAttributes(this.getSelectionStart(), this.getSelectionEnd()-this.getSelectionStart(), boldStyle, false);  

The bold style is set up like so:

boldStyle = this.addStyle("Bold", null);
StyleConstants.setBold(boldStyle, true);   

What I would like to know, is if it is possible to get the style for the currently selected text, so that if a user attempts to "bold" some text that is already bold, I can detect this and write code to un-bold this text instead of simply applying the bold style to it again?

Something like:

if(!this.getStyledDocument().getStyleForSelection(this.getSelectionStart(), this.getSelectionEnd()-this.getSelectionStart()).isBold()){
//do bold
}
else{
//un-bold
}

Would be a dream come true, but I have no hope for this. What I'm realistically hoping for is to either be told I'm doing it wrong and be shown "the way", or to be pointed in the direction of a round-a-bout method of achieving this.

Thank you very much for your time.

Upvotes: 2

Views: 2497

Answers (2)

Sriram S
Sriram S

Reputation: 543

Getting the Bold and Italic Styles From the JTextPane's Selectedtext

int start = jTextpane.getSelectionStart();
int end = jTextpane.getSelectionEnd();
String selectedText = jTextpane.getSelectedText();

Applying Style

StyledDocument doc = (StyledDocument) jTextpane.getDocument();
Style logicalStyle = doc.getLogicalStyle(jTextpane.getSelectionStart());
Element element = doc.getCharacterElement(start);
AttributeSet as = element.getAttributes();
Checking the Text,which is Bold and Italic

boolean isBold = StyleConstants.isBold(as) ? false : true;
boolean isItalic = StyleConstants.isItalic(as);
System.out.println("selected value is isItalic?"+isItalic);
System.out.println("selected value is isBold?"+isBold);

Upvotes: 2

McDowell
McDowell

Reputation: 108859

The easiest way to do this is via the StyledEditorKit:

JTextPane text = new JTextPane();
JButton button = new JButton("bold");
button.addActionListener(new StyledEditorKit.BoldAction());

JFrame frame = new JFrame("Styled");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(text, BorderLayout.CENTER);
frame.setSize(600, 400);
frame.setVisible(true);

Upvotes: 4

Related Questions