[英]How do I easily edit the style of the selected text in a JTextPane?
如何在JTextPane中輕松編輯所選文本的樣式? 這方面似乎沒有太多資源。 即使你可以指導我獲得一個很好的資源,我也非常感激。
另外,如何獲取所選文本的當前樣式? 我試過styledDoc.getLogicalStyle(textPane.getSelectionStart());
但它似乎沒有起作用。
這是一個插入格式化的“Hello World!”的代碼片段。 JEditorPane
字符串:
Document doc = yourEditorPane.getDocument();
StyleContext sc = new StyleContext();
Style style = sc.addStyle("yourStyle", null);
Font font = new Font("Arial", Font.BOLD, 18);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setFontFamily(style, font.getFamily());
StyleConstants.setBold(style, true);
doc.insertString(doc.getLength(), "Hello World!", style);
看看這個pastebin中的以下代碼:
http://pbin.oogly.co.uk/listings/viewlistingdetail/d6fe483a52c52aa951ca15762ed3d3
這個例子來自這里:
http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample3.htm
看起來您可以在動作偵聽器中使用以下內容更改樣式:
final Style boldStyle = sc.addStyle("MainStyle", defaultStyle);
StyleConstants.setBold(boldStyle, true);
doc.setCharacterAttributes(0, 10, boldStyle, true);
它將給定偏移量和長度之間的文本樣式設置為特定樣式。
有關詳細信息,請參閱完整的pastebin。 這應該可以解決你的問題。
操作文本面板的最簡單方法是使用編輯器工具包及其相關操作 。 您可以在JDK示例中找到此演示(在jdk \\ demo \\ jfc \\ Stylepad下 )。
安裝StyledEditorKit並使用FontSizeAction操作文本的示例代碼:
public static void main(String[] args) {
// create a rich text pane
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// install the editor kit
StyledEditorKit editorKit = new StyledEditorKit();
textPane.setEditorKit(editorKit);
// build the menu
JMenu fontMenu = new JMenu("Font Size");
for (int i = 48; i >= 8; i -= 10) {
JMenuItem menuItem = new JMenuItem("" + i);
// add an action
menuItem
.addActionListener(new StyledEditorKit.FontSizeAction(
"myaction-" + i, i));
fontMenu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(fontMenu);
// show in a frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setJMenuBar(menuBar);
frame.setContentPane(scrollPane);
frame.setVisible(true);
}
(提示:如果要使用FontFamilyAction ,請查看GraphicsEnvironment.getAvailableFontFamilyNames()和邏輯字體系列名稱 。)
我建議看看Sun的Java Tutorial有關編輯器窗格的內容。
好的,哇 難以回答的問題。 所以我還沒有找到一種方法來獲得給定角色的風格。 但是,您可以獲取給定字符的MutableAttributeSet,然后測試該樣式是否在該屬性集中。
Style s; //your style
Element run = styledDocument.getCharacterElement(
textPane.getSelectionStart() );
MutableAttributeSet curAttr =
( MutableAttributeSet )run.getAttributes();
boolean containsIt = curAttr.containsAttributes( s );
獲取一系列字符的樣式的一個問題是可能有多個樣式應用於該范圍(例如:您可以選擇文本,其中一些是粗體而一些不是)。
要更新所選文本,您可以:
Style s; //your style
JTextPane textPane; //your textpane
textPane.setCharacterAttributes( s, false );
哦,似乎函數getLogicalStyle不起作用,因為它返回包含p的段落的默認樣式(或者可能只是樣式),而不是p處的字符樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.