我正在尋找一種方法來做到以下幾點:擺動:自動調整大小按鈕上方的文本?
有一個固定寬度的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