2009-06-02 55 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