2014-11-03 37 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