有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    我用的是RTFEditorKit。所以我改变了密码:

    static Point getLocation(int pos,
                JEditorPane editorPane)
                throws BadLocationException {
    
            View view = editorPane.getUI().getRootView(editorPane);
            int index;
            while ((index = view.getViewIndex(pos, Position.Bias.Backward)) >= 0) {
                view = view.getView(index);
            }
    
            AttributeSet set = view.getAttributes();
            if (set != null && set.getAttribute(StyleConstants.FontFamily) != null) {
                Font f = new Font((String) set.getAttribute(StyleConstants.FontFamily), Font.PLAIN, (Integer) set.getAttribute(StyleConstants.FontSize));
                FontMetrics metrics = editorPane.getFontMetrics(f);
    
                Rectangle rect = editorPane.modelToView(pos);
                return new Point(rect.x,
                        rect.y + rect.height - metrics.getDescent() - metrics.getAscent());
            }
            else {
                return new Point(0, 0);
            }
        }
    

    但我总是看到当前字体的上升,而不是最大字体的上升

  2. # 2 楼答案

    由于一行中的所有字体共享一个基线*,因此可以通过调用modelToView并从矩形底部减去下降和上升来计算角色的视觉位置

    由于涉及多种字体,JEditorPane的getFont方法显然是不够的。文档的原始元素属性也不足,因为HTMLDocument的属性只是对HTML元素本身进行建模。但是,任何文档位置的实际字体都可以从相应的View中获得:

    static Point getLocation(int pos,
                             JEditorPane editorPane)
    throws BadLocationException {
    
        HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
    
        View view = editorPane.getUI().getRootView(editorPane);
        int index;
        while ((index = view.getViewIndex(pos, Position.Bias.Backward)) >= 0) {
            view = view.getView(index);
        }
    
        AttributeSet attr = doc.getStyleSheet().getViewAttributes(view);
        Font f = doc.getStyleSheet().getFont(attr);
    
        FontMetrics metrics = editorPane.getFontMetrics(f);
        Rectangle rect = editorPane.modelToView(pos);
    
        return new Point(rect.x,
            rect.y + rect.height - metrics.getDescent() - metrics.getAscent());
    }
    

    *为了简单起见,我忽略了有悬挂基线和垂直基线的字符

    编辑:由于RTFEditorKit很少使用,我错误地认为您使用的是HTMLEditorKit。这将适用于RTF文档:

    static Point getLocation(int pos,
                         JEditorPane editorPane)
    throws BadLocationException {
        StyledDocument doc = (StyledDocument) editorPane.getDocument();
        View view = editorPane.getUI().getRootView(editorPane);
        int index;
        while ((index = view.getViewIndex(pos, Position.Bias.Backward)) >= 0) {
            view = view.getView(index);
        }
    
        AttributeSet attr = view.getAttributes();
        Font f = doc.getFont(attr);
    
        FontMetrics metrics = editorPane.getFontMetrics(f);
        Rectangle rect = editorPane.modelToView(pos);
    
        return new Point(rect.x,
            rect.y + rect.height - metrics.getDescent() - metrics.getAscent());
    }