如何解决如何知道 JTextArea 中包含的文本的高度?
我已经使用过 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);
解决方法
(如果我理解你的问题)
只需将 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。