2009-06-02 58 views
3

假设我有一个显示HTML文档的JTextPane。增加显示HTML文本的JTextPane的字体大小

我想要的是,在按下按钮时,文档的字体大小会增加。

不幸的是,这并不像看起来那么容易... 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。我想要的是字体大小按照与文档中已有内容成比例的比例增加。

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

回答

1

您可能可以使用css并只修改样式字体。

因为它呈现HTML原样,所以更改css类可能就足够了。

4

在你链接到你的例子中,你会发现你想要做的一些线索。

线

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

改变的JTextPane的字体大小,并将其设置到您作为参数传递给此方法的字体的大小。您想要根据当前尺寸将其设置为新的尺寸。

//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字体的大小增加一倍。你当然可以以较慢的速度增加。

现在你想要一个按钮来调用你的方法。

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

所以,你可以写一个类似的例子是这样的方法:

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); 
} 
+0

他想的是“字体大小成比例的规模了已经在文档中增加。 “但是,您的示例将文档中的所有字体设置为相同的大小。 – ka3ak 2013-02-28 06:02:48