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

eh57zj3b  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(194)

我已经使用了getPreferredSize()getSize()getMaximumSize()getMinimumSize()。但是它们都没有给予我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);
dm7nw8vv

dm7nw8vv1#

我发现textArea.getPreferredScrollableViewportSize()非常有帮助-它包含了文本字段在没有滚动的情况下需要完全显示的区域。

pkmbmrz7

pkmbmrz72#

(If我理解你的问题)
只需将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);
    }
}

相关问题