假设我有一个显示 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 .我想要的是字体大小与文档中已有的内容成比例地增加。
我是否必须遍历文档中的每个元素、获取字体大小、计算新大小并将其设置回去?我该怎么做这样的操作?什么是最好的方法?
最佳答案
在您链接到的示例中,您会发现一些关于您正在尝试做什么的线索。
线
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);
}
关于java - 增加显示 HTML 文本的 JTextPane 的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/939109/