Getting the height of JTextPane content

1k views Asked by At

The main idea is to draw a specific form, using Swing library(it will be used to generate an image, which will be transfered to a escpos printer, but thats another question). The form itself has a full width container at the top, which represents the label. The label has a custom font, font size and can have a linewrap, therefor i used JTextPane. JTextPane element, and all of the form, will have a fixed size of 500px.

As a test, the code looks like:

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);

The question is, how do i calculate JTextPane's full size, in order to set its height to the container, which is holding it? The part where i hardcodedly try to give out a height correction, even worked, but then i added a font...

2

There are 2 answers

1
Sharcoux On BEST ANSWER

I wrote a detailed answer on a similar question. Check here

The idea is that getPreferredSize().height called on a JTextPane will return the height needed to display the current content given the current width. If the width is not set yet, it will return the height needed if the width of the JTP was the width of the longest line.

With the same logic, getPreferredSize().width will return the width of the longest line.

0
Draaksward On

For those who maybe struck on the same problem(or just curious). Found a solution here: link

The idea came to be quite simple:

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