Swing:自动调整按钮上方的文本大小?

时间:2014-11-03 09:20:59

标签: java swing layout

我正在寻找以下方法:

拥有固定宽度的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();


}

包装两次对我来说似乎有点奇怪,但它确实解决了调整大小问题:)。

1 个答案:

答案 0 :(得分:3)

尝试使用此方法根据其模型调整TextArea的大小。

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