获取 JTextPane 内容的高度

Getting the height of JTextPane content

主要思路是绘制一个特定的表格,使用Swing库(它将用于生成图像,将其传输到escpos打印机,但那是另一个问题)。表单本身在顶部有一个全宽容器,代表标签。该标签具有自定义字体、字体大小并且可以有换行,因此我使用了 JTextPane。 JTextPane 元素和所有表单的大小固定为 500 像素。

作为测试,代码如下所示:

JFrame fr = getFrame();

    JPanel root = new JPanel(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();

    JPanel titleP = new JPanel(new BorderLayout());
    titleP.setBorder(BorderFactory.createTitledBorder("titleP"));
    c.fill = GridBagConstraints.BOTH;
    c.gridy = 0;
    c.gridx = 0;
    c.gridwidth = 8;
    c.weightx = 1.0f;
    c.weighty = 1.0f;

    JTextPane tp = new JTextPane();
    JScrollPane sp = new JScrollPane(tp);
    Font font = new Font("Arial",Font.BOLD, 37);
    tp.setFont(font);
    tp.setText("fdsfdsf sdf sdf sd fdsfsdf sdf sd fsd fdsf sdf sdf sdf sdf sdf sdf sdf ds");
    tp.setOpaque(false);
    titleP.add(sp);

    root.add(titleP,c);

    JPanel infoP = new JPanel();
    infoP.setBorder(BorderFactory.createTitledBorder("infoP"));

    c.gridwidth = 5;
    c.gridy = 1;
    c.gridx = 0;

    //infoP.setPreferredSize(new Dimension(350,200));

    root.add(infoP,c);

    JPanel priceP = new JPanel();
    priceP.setBorder(BorderFactory.createTitledBorder("priceP"));

    c.gridx = 5;
    c.gridwidth = 3;

    root.add(priceP,c);

    fr.setContentPane(root);
    fr.pack();

    int size1 = fr.getHeight();
    int width = 120;
    fr.setSize(width, 0);
    size1 += tp.getHeight();
    size1 += 25;
    fr.setSize(width, size1);
    fr.setVisible(true);

问题是,我如何计算 JTextPane 的完整大小,以便将其高度设置为容纳它的容器?我硬编码尝试给出高度校正的部分,甚至工作,但后来我添加了一个字体...

对于那些可能遇到同样问题(或只是好奇)的人。在这里找到了解决方案:link

这个想法变得非常简单:

public int getContentHeight(int width, String content) {
    JEditorPane dummyEditorPane = new JEditorPane();
    dummyEditorPane.setSize(width, Short.MAX_VALUE);
    dummyEditorPane.setText(content);
    return dummyEditorPane.getPreferredSize().height;
}

我写了一个类似问题的详细答案。检查 here

想法是在给定当前宽度的情况下,在 JTextPane 上调用的 getPreferredSize().height 将 return 显示当前内容所需的高度。如果尚未设置宽度,如果 JTP 的宽度是最长线的宽度,它将 return 所需的高度。

同理,getPreferredSize().width 会return最长线的宽度。