简体   繁体   English

如何在JTextPane中获得所选文本的样式?

[英]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. 我正在尝试创建一个简单的WYSIWYG编辑器,该编辑器将允许用户选择文本并将其加粗/加下划线/斜体。 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. 非常感谢您的宝贵时间。

The easiest way to do this is via the StyledEditorKit : 最简单的方法是通过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 从JTextPane的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM