增加显示HTML文本的JTextPane的字体大小 [英] Increasing the font size of a JTextPane that displays HTML text

查看:490
本文介绍了增加显示HTML文本的JTextPane的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个显示HTML文档的JTextPane。

Lets say that I have a JTextPane that is showing a HTML document.

我想要的是,按一下按钮,文档的字体大小为增加。

I want that, on the press of a button, the font size of the document is increased.

不幸的是,这并不像看起来那么容易...... 我找到了一种方法来改变整个文档的字体大小,但这意味着所有文本都设置为我指定的字体大小。我想要的是字体大小按照文档中已有的比例增加。

Unfortunately this is not as easy as it seems... I found a way to change the font size of the whole document, but that means that all the text is set to the font size that I specify. What I want is that the font size is increased in a proportional scale to what was already in the document.

我是否必须迭代文档上的每个元素,得到字体大小,计算新的大小并将其设置回来?我该怎么办这样的手术?最好的方法是什么?

Do I have to iterate over every element on the document, get the font size, calculate a new size and set it back? How can I do such an operation? What is the best way?

推荐答案

在您链接到的示例中,您将找到一些线索,告诉您要执行的操作。

In the example that you linked to you will find some clues to what you are trying to do.

该行

StyleConstants.setFontSize(attrs, font.getSize());

更改JTextPane的字体大小并将其设置为您传递的字体大小此方法的参数。您希望根据当前大小将其设置为新大小。

changes the font size of the JTextPane and sets it to the size of the font that you pass as a parameter to this method. What you want to to set it to a new size based on the current size.

//first get the current size of the font
int size = StyleConstants.getFontSize(attrs);

//now increase by 2 (or whatever factor you like)
StyleConstants.setFontSize(attrs, size * 2);

这将导致JTextPane的字体大小翻倍。你当然可以以较慢的速度增加。

This will cause the font of the JTextPane double in size. You could of course increase at a slower rate.

现在你需要一个可以调用你的方法的按钮。

Now you want a button that will call your method.

JButton b1 = new JButton("Increase");
    b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            increaseJTextPaneFont(text);
        }
    });

所以你可以编写一个类似于示例中的方法,如下所示:

So you can write a method similar to the one in the example like this:

public static void increaseJTextPaneFont(JTextPane jtp) {
    MutableAttributeSet attrs = jtp.getInputAttributes();
    //first get the current size of the font
    int size = StyleConstants.getFontSize(attrs);

    //now increase by 2 (or whatever factor you like)
    StyleConstants.setFontSize(attrs, size * 2);

    StyledDocument doc = jtp.getStyledDocument();
    doc.setCharacterAttributes(0, doc.getLength() + 1, attrs, false);
}

这篇关于增加显示HTML文本的JTextPane的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆