【问题标题】:Detecting Styled Text in a Document检测文档中的样式文本
【发布时间】:2013-12-02 10:55:23
【问题描述】:

我有一个 JTextPane 供用户编写日记条目,他们可以通过选择文本并选择粗体或斜体等菜单项来设置样式。这些项目连接到样式编辑器工具包之一(例如 StyledEditorKit.BoldAction() )。

是否有任何方法可以检测给定文档位置的文本是否已使用这些工具包之一进行样式设置?如果是的话怎么办?

       //Create the style menu.
protected JMenu createStyleMenu() {
    JMenu menu = new JMenu("Style");

    Action action = new StyledEditorKit.BoldAction();  
    action.putValue(Action.NAME, "Bold");        
    menu.add(action);

    action = new StyledEditorKit.ItalicAction();
    action.putValue(Action.NAME, "Italic");
    menu.add(action);

    action = new StyledEditorKit.UnderlineAction();
    action.putValue(Action.NAME, "Underline");
    menu.add(action);

    menu.addSeparator();

    menu.add(new StyledEditorKit.FontSizeAction("12", 12));
    menu.add(new StyledEditorKit.FontSizeAction("14", 14));
    menu.add(new StyledEditorKit.FontSizeAction("18", 18));
    menu.add(new StyledEditorKit.FontSizeAction("36", 36));

    menu.addSeparator();

    menu.add(new StyledEditorKit.FontFamilyAction("Serif",
                                                  "Serif"));
    menu.add(new StyledEditorKit.FontFamilyAction("SansSerif",
                                                  "SansSerif"));

    menu.addSeparator();

    menu.add(new StyledEditorKit.ForegroundAction("Red",
                                                  Color.red));
    menu.add(new StyledEditorKit.ForegroundAction("Green",
                                                  Color.green));
    menu.add(new StyledEditorKit.ForegroundAction("Blue",
                                                  Color.blue));
    menu.add(new StyledEditorKit.ForegroundAction("Black",
                                                  Color.black));

    return menu;
}

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing text styleddocument


【解决方案1】:

可以查询文档中某个字符的属性:

StyledDocument doc = (StyledDocument)textPane.getDocument();
Element element = doc.getCharacterElement(position);

Boolean isItalic = element.getAttributes().getAttribute(StyleConstants.Italic);

【讨论】:

  • 感谢您的信息。第 2 行和第 3 行的语法有问题。但是,我大致了解了您的建议,并根据您的建议提出了此代码:StyledDocument doc = (StyledDocument) gui.txpEntryText.getDocument(); Element element = doc.getCharacterElement(1); System.out.print("Bold = " + element.getAttributes().getAttribute(StyleConstants.Bold));
  • 对不起,我刚刚看到我的代码有错误(已经修复)。请注意,您还可以使用其他方法 getParagraphElementgetLogicalStyle
  • 没问题。我发现您的代码真的很有帮助(也感谢您提供的其他信息)。您原始回复中的最后一行代码有一点问题。这部分很好 - element.getAttributes().getAttribute(StyleConstants.Italic);,但它不允许我将它分配给布尔变量。它说类型不兼容(这很奇怪,因为它返回了一个真/假值)。但是,它让我这样做了 - if (elmt.getAttributes().getAttribute(StyleConstants.Bold) == true) strFormattingData[0] = "true"; - 所以我就这样解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2015-05-21
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多