2014-11-03 83 views
1

我正在尋找一種方法來做到以下幾點:擺動:自動調整大小按鈕上方的文本?

有一個固定寬度的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(); 


} 

包裝兩次仍似乎有點怪我,但它確實解決了大小調整的問題:)。

+0

我想念那裏JScrollPane的,休息甲骨文步道如何使用的JTextArea/JScrollPane的 – mKorbel 2014-11-03 09:26:07

+0

使用HTML知曉組件和CSS來限制寬度。該組件將會像它需要的一樣高。查看[這個答案](http://stackoverflow.com/a/5767825/418556)演示。 – 2014-11-03 09:34:26

+0

我只是現在嚴重懷疑我的理智:正如上面的固定代碼所示,Ezequiel的代碼似乎沒有做任何事情,因爲它僅僅調用pack()TWICE而不是一次...是一個Java錯誤,我在技術上不應該這樣做,或者它應該如何運作? – Layna 2014-11-03 11:27:35

回答

3

試試這個方法來調整基於模型的JTextArea的大小。

 Rectangle modelToView = area.modelToView(area.getDocument().getLength()); 
     if (modelToView != null) { 
      area.setSize(area.getWidth(), Math.max(area.getHeight(), modelToView.height + modelToView.y)); 
      area.doLayout(); 
     } 
+0

這看起來很有希望,但我得到了modelToView方法的空值。 Javadoc聲明「在組件大小調整之前不能計算佈局」。我懷疑這可能是問題所在,但是不會讓我回到原始問題:確定JTextArea的大小是多少? – Layna 2014-11-03 09:35:22

+0

嘗試在打包jframe後使用這些行。 – Ezequiel 2014-11-03 09:37:58

+0

現在,它的工作...關鍵是打包(),然後使用代碼,然後再次打包。這麼多的包裝,但它現在起作用!謝謝 :) – Layna 2014-11-03 09:42:26