如何知道 JTextArea 中包含的文本的高度?

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

我已经使用了 getPreferredSize()getSize()getMaximumSize()getMinimumSize()。但是 none 给了我 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);

(如果我理解你的问题)

只需将 textArea 上存在的行数和每行的高度相乘即可:

一个例子:

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