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

I am trying to create a simple WYSIWYG editor that will allow users to select text and bold / underline / highlight it. Currently, the user can select text, right-click and bold from the pop-up menu, which will make the bold highlight like this:

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

      

The bold style is configured like this:

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 the user tries to "boldly" select some text that is already selected, I can detect it and write code for not bold this text instead of bold style again?

Something like:

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

      

It would be a dream, but I don't hope so. What I was really hoping for was either to say that I was doing it wrong and showing the "way" or pointing in the direction of the "round arc" method of achieving this.

Thanks a lot for your time.

+2


source to share


2 answers


The easiest way to do this is with 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);

      

+4


source


Getting bold and italic styles from selected JTextPane text

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

      



Applying a 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);

      

+2


source







All Articles