Lately I have been using Style Constants, Styled Documents and Text Pane. I know that you can edit a part of the text that you highlight/select showing it in the code below
StyledDocument doc = this.tpText.getStyledDocument();
Style style = this.tpText.addStyle("stylish", null);
StyleConstants.setForeground(style, color.BLACK);
StyleConstants.setFontFamily(style, "Arial");
doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("stylish"), true);//This is the piece of code (last line) that will set all the attributes to the highlited text.
As an example, if the user highlights/selects "o worl" in "hello world", just the "o worl" will be changed to color black and the font letter will be Arial.
Now, my question is: how can you get the font letter and color from a highlihted/selected text? I want to know how can I save that in seperate variables (one for color and the other for the font letter).
Ok, after doing more research I found out the answer.
doc = this.tpText.getStyledDocument();
Element element = doc.getCharacterElement(this.tpText.getSelectionStart());
AttributeSet as = element.getAttributes();
colour = StyleConstants.getForeground(as);
The only downside I see about this Style Constant method is that it will only recognize the first character attribute and overwrite/ignore the other ones. Maybe with a loop I can do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.