草庐IT

java - 是否可以在 JEditorPane 中缩放/缩放字体大小(和图像大小)

coder 2024-04-02 原文

有没有可能在JEditorPane中以某种方式缩放文本和图片。

我不喜欢遍历所有 HTML 页面来使字体变大。

最佳答案

我定制了 HTMLEditorKit,它可以放大/缩小 JEditorPane 的 HTML 内容,它具有更好的渲染性能,我称之为 LargeHTMLEditorKit:

/**
 * An extended {@link HTMLEditorKit} that allow faster
 * rendering of large html files and allow zooming of content.
 * @author Alessio Pollero
 * @version 1.0
 */
public class LargeHTMLEditorKit extends HTMLEditorKit {

     ViewFactory factory = new MyViewFactory();

        @Override
        public ViewFactory getViewFactory() {
            return factory;
        }

        class MyViewFactory extends HTMLFactory {
            @Override
            public View create(Element elem) {
                AttributeSet attrs = elem.getAttributes();
                Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
                Object o = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
                if (o instanceof HTML.Tag) {
                    HTML.Tag kind = (HTML.Tag) o;
                    if (kind == HTML.Tag.HTML) {
                        return new HTMLBlockView(elem);
                    }
                    else if (kind == HTML.Tag.IMPLIED) {
                        String ws = (String) elem.getAttributes().getAttribute(CSS.Attribute.WHITE_SPACE);
                        if ((ws != null) && ws.equals("pre")) {
                            return super.create(elem);
                        }
                        return new HTMLParagraphView(elem);
                    } else if ((kind == HTML.Tag.P) ||
                            (kind == HTML.Tag.H1) ||
                            (kind == HTML.Tag.H2) ||
                            (kind == HTML.Tag.H3) ||
                            (kind == HTML.Tag.H4) ||
                            (kind == HTML.Tag.H5) ||
                            (kind == HTML.Tag.H6) ||
                            (kind == HTML.Tag.DT)) {
                        // paragraph
                        return new HTMLParagraphView(elem);
                    }
                }
                return super.create(elem);
            }

        }


        private class HTMLBlockView extends BlockView {

            public HTMLBlockView(Element elem) {
                super(elem,  View.Y_AXIS);
            }

            @Override
            protected void layout(int width, int height) {
                if (width<Integer.MAX_VALUE) {
                    super.layout(new Double(width / getZoomFactor()).intValue(),
                             new Double(height *
                                        getZoomFactor()).intValue());
                }
            }

            public double getZoomFactor() {
                Double scale = (Double) getDocument().getProperty("ZOOM_FACTOR");
                if (scale != null) {
                    return scale.doubleValue();
                }

                return 1;
            }

            @Override
            public void paint(Graphics g, Shape allocation) {
                Graphics2D g2d = (Graphics2D) g;
                double zoomFactor = getZoomFactor();
                AffineTransform old = g2d.getTransform();
                g2d.scale(zoomFactor, zoomFactor);
                super.paint(g2d, allocation);
                g2d.setTransform(old);
            }

            @Override
            public float getMinimumSpan(int axis) {
                float f = super.getMinimumSpan(axis);
                f *= getZoomFactor();
                return f;
            }

            @Override
            public float getMaximumSpan(int axis) {
                float f = super.getMaximumSpan(axis);
                f *= getZoomFactor();
                return f;
            }

            @Override
            public float getPreferredSpan(int axis) {
                float f = super.getPreferredSpan(axis);
                f *= getZoomFactor();
                return f;
            }

            @Override
            public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
                double zoomFactor = getZoomFactor();
                Rectangle alloc;
                alloc = a.getBounds();
                Shape s = super.modelToView(pos, alloc, b);
                alloc = s.getBounds();
                alloc.x *= zoomFactor;
                alloc.y *= zoomFactor;
                alloc.width *= zoomFactor;
                alloc.height *= zoomFactor;

                return alloc;
            }

            @Override
            public int viewToModel(float x, float y, Shape a,
                                   Position.Bias[] bias) {
                double zoomFactor = getZoomFactor();
                Rectangle alloc = a.getBounds();
                x /= zoomFactor;
                y /= zoomFactor;
                alloc.x /= zoomFactor;
                alloc.y /= zoomFactor;
                alloc.width /= zoomFactor;
                alloc.height /= zoomFactor;

                return super.viewToModel(x, y, alloc, bias);
            }

        }
}

这是必需的 HTMLParagraphView :

class HTMLParagraphView extends ParagraphView {

     public static int MAX_VIEW_SIZE=100;

        public HTMLParagraphView(Element elem) {
            super(elem);
            strategy = new HTMLParagraphView.HTMLFlowStrategy();
        }

        public static class HTMLFlowStrategy extends FlowStrategy {
            protected View createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) {
                View res=super.createView(fv, startOffset, spanLeft, rowIndex);
                if (res.getEndOffset()-res.getStartOffset()> MAX_VIEW_SIZE) {
                    res = res.createFragment(startOffset, startOffset+ MAX_VIEW_SIZE);
                }
                return res;
            }

        }
        public int getResizeWeight(int axis) {
            return 0;
        }
}

然后你可以这样使用它:

//Create a new JEditorPane
JEditorPane yourPane = new JEditorPane();
//Set the custom HTMLEditorKit
yourPane.setEditorKit(new LargeHTMLEditorKit());
//Set the zoom to 150%
yourPane.getDocument().putProperty("ZOOM_FACTOR", new Double(1.5));

关于java - 是否可以在 JEditorPane 中缩放/缩放字体大小(和图像大小),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/680817/

有关java - 是否可以在 JEditorPane 中缩放/缩放字体大小(和图像大小)的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  3. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  6. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  7. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  8. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  9. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  10. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

随机推荐