簡體   English   中英

JTextPane - 如何設置所選文本的樣式

[英]JTextPane - how to style selected text

我正在尋找最簡單的方法來控制所選文本中的JTextPane(其內部文本)字體顏色和字體大小。

我知道我必須看看StyledDocument但它的片段顯示JMenu動作監聽器技巧但不是JButton :(

我找不到可以顯示如何通過單擊JButton(actionPerformed(...)方法)等來更改所選文本樣式的代碼片段:(

我的意思是朝這個方向發展

  • A)我在JTextPane中有一個文本,可以說“我的家就是變成borabora,這是......”
  • B)在JTextPane中選擇文本“borabora”
  • C)點擊JButton(“size = 16”)
  • D)文本“borabora”大小變為16

我找不到這種片段,所以我需要你的建議。

任何有用的評論表示贊賞

在適用的jbutton的actionPerformed方法中,你可以運行它。 (根據需要修改。)

String text = jTextPane.getSelectedText();
int cursorPosition = jTextPane.getCaretPosition();

StyleContext context = new StyleContext();
Style style;

jTextPane.replaceSelection("");

style = context.addStyle("mystyle", null);
style.addAttribute(StyleConstants.FontSize, new Integer(16));
jTextPane.getStyledDocument().insertString(cursorPosition - text.length(), text, style);

但它的片段顯示了JMenu動作監聽器技巧但不是JButton

您可以將動作添加到JButton以及JMenu。 例如:

Jbutton button = new JButton( new StyledEditorKit.FontSizeAction("16", 16) );

如果要將多個屬性同時應用於一段文本,則可以使用樣式。

根據@scartag的答案和關於API的評論(來自@kleopatra),我找到了另一種方法。

StyleContext context = new StyleContext();
Style style = context.addStyle("mystyle", null);
style.addAttribute(StyleConstants.FontSize, new Integer(16));;
jTextPane.setCharacterAttributes(style , true);

方法setCharacterAttributes(style, replace)更改所選文本的樣式,因此您無需將其刪除並再次使用新樣式添加。 而且,boolean replace表示樣式是否替換舊樣式( true )或者是否添加到舊樣式( false )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM