簡體   English   中英

如何在JTextPane中獲得所選文本的樣式?

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

我正在嘗試創建一個簡單的WYSIWYG編輯器,該編輯器將允許用戶選擇文本並將其加粗/加下划線/斜體。 當前,用戶可以選擇文本,單擊鼠標右鍵,然后從彈出菜單中選擇粗體,最終將粗體樣式應用於所選文本,如下所示:

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

粗體樣式設置如下:

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

我想知道的是,是否有可能獲取當前所選文本的樣式,以便如果用戶嘗試“加粗”某些已經為粗體的文本,我可以檢測到此並將代碼寫為非粗體而不是簡單地再次將粗體樣式應用於此文本?

就像是:

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

夢想成真,但我對此沒有希望。 我實際上希望的是被告知我做錯了事並被“指明”方向,或者被指向實現這一目標的全面方法的方向。

非常感謝您的寶貴時間。

最簡單的方法是通過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);

從JTextPane的Selectedtext獲取粗體和斜體樣式

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

適用風格

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