如何衡量/计算文档需要自行渲染的大小? [英] How can I measure/calculate the size a Document needs to render itself?
本文介绍了如何衡量/计算文档需要自行渲染的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 javax.swing.text.Document
,我想计算文档需要自我渲染的边界框的大小。
I have a javax.swing.text.Document
and I want to calculate the size of the bounding box that document needs to render itself.
这可能吗?
纯文本几乎是微不足道的(身高=行数*行高
, width =每行的最大宽度
)但是如何使用RTF,HTML或任何其他文档执行此操作?
It is almost trivial for plain text (height = line count * line height
, width = max width over each line
) But how can I do this with RTF, HTML or any other document?
推荐答案
这段代码可能会给你一些想法:
This code might give you some ideas:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPanePerfectSize extends JFrame
{
JTextField textField;
JTextPane textPane;
public TextPanePerfectSize()
{
textField = new JTextField(20);
textField.setText("add text");
getContentPane().add(textField, BorderLayout.NORTH );
textField.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), " " + textField.getText(), null);
textField.setText("");
Dimension d = textPane.getPreferredSize();
Rectangle r = textPane.modelToView( textPane.getDocument().getLength() );
d.height = r.y + r.height;
textPane.setPreferredSize( d );
getContentPane().validate();
// pack();
}
catch(Exception e2) {}
}
});
JLabel label = new JLabel("Hit Enter to Add Text to Text Pane");
getContentPane().add(label);
JPanel south = new JPanel();
textPane = new JTextPane();
textPane.setText("Some text");
textPane.setEditable( false );
// textPane.setPreferredSize( new Dimension(120, 23) );
south.add( textPane );
// getContentPane().add(south, BorderLayout.SOUTH);
getContentPane().add(textPane, BorderLayout.SOUTH);
}
public static void main(String[] args)
{
JFrame frame = new TextPanePerfectSize();
frame.setSize(200, 200);
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
这篇关于如何衡量/计算文档需要自行渲染的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文