【发布时间】:2021-09-01 11:25:48
【问题描述】:
我已经使用过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);
【问题讨论】:
-
能否提供您使用的代码。这个主题的问题通常发生在你 getSize() 之前这些有实际大小,例如你在它渲染之前调用 getSize 或调用 pack() 或在根容器上设置可见。另一个原因是大小会随您使用的布局而变化。
-
@ntprintf 完成..
-
不要使用空布局或 AbsoluteLayout。 Swing 旨在与布局管理器一起使用。发布 minimal reproducible example 来展示您的问题。
-
(1-) 这个问题无法回答,因为 OP 没有提供问题的完整上下文。有关完整上下文,请参阅 OP 的最后一个问题:stackoverflow.com/questions/68003700/…
-
@camickr 啊,对不起,我是新来的……感谢您指出最佳的发帖方式。也感谢您的回答,这有助于我今天找到答案。我已经再次更改了我的布局管理器,而不是 null 或 absolute,而是使用框布局。为了获得 jTextarea 的高度,我手动计算它,因为我的宽度是恒定值,所以我可以使用下面 George 的逻辑来计算它。