javaswingjtextarea

How to know the height of the text contained in JTextArea?


I already used getPreferredSize(), getSize(), getMaximumSize(), and getMinimumSize(). But none of them give me an accurate height of the text in the JTextArea.

JTextArea txt = new JTextArea();
txt.setColumns(20);
txt.setLineWrap(true);
txt.setRows(1);
txt.setToolTipText("");
txt.setWrapStyleWord(true);
txt.setAutoscrolls(false);
txt.setBorder(null);
txt.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
add(txt, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 40, 540, -1));
JOptionPane.ShowMessageDialog(null, txt.getPreferredSize().height);

Solution

  • (If I understood your question)

    Just take the number of lines that exist on the textArea and the height of each line and multiply them:

    An example:

    public class ProductsFrame extends JFrame {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(ProductsFrame::runExample);
        }
    
        private static void runExample() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea textArea = new JTextArea(10, 10);
    
            frame.setLayout(new BorderLayout());
    
            frame.add(new JScrollPane(textArea));
    
            textArea.addCaretListener(e -> {
                int linesWithText = textArea.getLineCount();
                int heightOfEachLine = textArea.getFontMetrics(textArea.getFont()).getHeight();
    
                int heightOfText = linesWithText * heightOfEachLine;
    
                System.out.println("TEXt HEIGHT:" + heightOfText);
                System.out.println("TEXT AREA HEIGHT:" + textArea.getSize().height);
            });
    
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    }