我正在寻找一种方法来做到以下几点:摆动:自动调整大小按钮上方的文本?
有一个固定宽度的JDialog。
在它是一个JTextArea(或任何你的建议是一个更好的组件......),其接收不同长度(介于0和30线)
下面的文本是一个按钮的文本。
该对话框的高度自动调整大小以确保所有文本和按钮正在显示。
最接近我的是一个解决方案是这样的,但JTextArea似乎并不知道自动换行符后它有多大!
public PleaseResize(){
super();
Container cp = this.getContentPane();
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
JTextArea area = new JTextArea();
area.setColumns(20);
area.setLineWrap(true);
area.setEditable(false);
area.setWrapStyleWord(true);
area.setText("Once upon a midnight dreary, while I pondered, weak and weary, over many a quaint an curious volume of forgotten lore.");
cp.add(area);
cp.add(new JButton("Hallo"));
this.pack();
}
滚动文字是不幸不一个选项。
我问过这里有一个稍微不同的方式:Resize Dialog properly after automatic LineWrap,但也许JTextArea毕竟是错误的组件?我是否使用错误的LayoutManager?尽管如此,他们似乎无法确定该对话框应该有多大。为什么JTextArea在文本向外部添加换行符后无法传达它的高度?
这里是工作代码:
public PleaseResize() throws BadLocationException {
super();
Container cp = this.getContentPane();
cp.setLayout(new BorderLayout());
JTextArea area = new JTextArea();
area.setColumns(20);
area.setLineWrap(true);
area.setEditable(false);
area.setWrapStyleWord(true);
area.setText("Once upon a midnight dreary, while I pondered, weak and weary, over many a quaint an curious volume of forgotten lore.");
System.out.println(area.getLineCount());
JScrollPane pane = new JScrollPane(area);
cp.add(pane, BorderLayout.CENTER);
cp.add(new JButton("Hallo"), BorderLayout.SOUTH);
this.pack();
this.pack();
}
包装两次仍似乎有点怪我,但它确实解决了大小调整的问题:)。
我想念那里JScrollPane的,休息甲骨文步道如何使用的JTextArea/JScrollPane的 – mKorbel 2014-11-03 09:26:07
使用HTML知晓组件和CSS来限制宽度。该组件将会像它需要的一样高。查看[这个答案](http://stackoverflow.com/a/5767825/418556)演示。 – 2014-11-03 09:34:26
我只是现在严重怀疑我的理智:正如上面的固定代码所示,Ezequiel的代码似乎没有做任何事情,因为它仅仅调用pack()TWICE而不是一次...是一个Java错误,我在技术上不应该这样做,或者它应该如何运作? – Layna 2014-11-03 11:27:35