Nat*_* W. 12 java swing jtextarea jtextcomponent
在我可以找到的所有使用a的例子中JTextArea,高度和宽度在构造之前是已知的JTextArea,如果JTextArea需要更多高度,那么它被放在a中JScrollPane.显然,高度JTextArea取决于宽度和文本内容.
现在,我的情况要求我不使用a JScrollPane,而是JTextArea要足够高以显示所有文本.当我创建时JTextArea,我知道文本内容以及它必须使用的宽度; 我不知道高度 - 我希望在不切断任何文本的情况下尽可能小.这似乎很难实现.
作为旁注,JTextArea将添加到JPanel没有布局管理器的 - 它使用基于添加的组件的首选大小的绝对定位.这要求我JTextArea将返回正确的尺寸getPreferredSize().正确的尺寸应该是我在构造时提供的宽度,以及显示具有所提供宽度的所有文本所需的最小高度.
我发现了一些类似的线程,讨论了有关的奇怪/错误JTextArea,有时通过pack()在父容器上调用两次来解决.这对我来说不是一个选择.我很想基本上创建我自己JTextArea的宽度和字符串,并根据宽度和字体设置计算必要的最小高度,但我想我会先考虑先花费时间才能做到这一点.
希望我的问题很明确.感谢大家的帮助!
它使用基于添加组件的首选大小的绝对定位.
听起来像布局管理员的工作.
这要求我的JTextArea将在getPreferredSize()上返回正确的维度.
JTextArea textArea = new JTextArea();
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setText("one two three four five six seven eight nine ten");
System.out.println("000: " + textArea.getPreferredSize());
textArea.setSize(100, 1);
System.out.println("100: " + textArea.getPreferredSize());
textArea.setSize( textArea.getPreferredSize() );
Run Code Online (Sandbox Code Playgroud)
import java.awt.*;
import javax.swing.*;
class FixedWidthLabel {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
String pt1 = "<html><body width='";
String pt2 =
"px'><h1>Label Height</h1>" +
"<p>Many Swing components support HTML 3.2 &" +
" (simple) CSS. By setting a body width we can cause the " +
" component to find the natural height needed to display" +
" the component.<br><br>" +
"<p>The body width in this text is set to " +
"";
String pt3 =
" pixels." +
"";
JPanel p = new JPanel( new BorderLayout() );
JLabel l1 = new JLabel( pt1 + "125" + pt2 + "125" + pt3 );
p.add(l1, BorderLayout.WEST);
JLabel l2 = new JLabel( pt1 + "200" + pt2 + "200" + pt3 );
p.add(l2, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, p);
}
};
SwingUtilities.invokeLater(r);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27790 次 |
| 最近记录: |