开发者

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

开发者 https://www.devze.com 2022-12-08 09:51 出处:网络
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

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.se开发者_Python百科tBold(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.


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号