java 设置 JTextArea 的固定宽度,而高度应根据其内容自动调整

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11018845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:27:10  来源:igfitidea点击:

Setting fixed width of JTextArea while height should be automatically adjusted to its content

javaswingjtextarea

提问by Michal Vician

When I run the sample code below the width of JTextArea is fixed (100px) while its height is dynamically adjusted as I type some text in it.

当我在 JTextArea 的宽度下方运行示例代码时,它的宽度是固定的(100px),而当我在其中输入一些文本时,它的高度会动态调整。

So for example I start with this:

例如,我从这个开始:

--------------------
| some text        |
--------------------

and as I type more text the height of JTextArea expands so it fits the content while preserving the width:

当我输入更多文本时,JTextArea 的高度会扩展,以便在保留宽度的同时适合内容:

--------------------
| some text, some  |
| other longer text|
| etc...           |
--------------------

How can I double the width of JTextArea? When I do it by changing preferredSizethe height is not dynamic anymore.

如何将 JTextArea 的宽度加倍?当我通过改变preferredSize高度来做到这一点时,它不再是动态的。

public class TestTextArea extends JFrame {

    public static void main(String[] args) {
        new TestTextArea().setVisible(true);
    }

    public TestTextArea() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0,0,800,600);
        setContentPane(createPane());
    }

    protected Container createPane() {
        JTextArea textArea = createTextArea();

        // ------------------------------------------
        // UNCOMMENT TO DOUBLE THE WIDTH OF JTextArea

//        Dimension oldPrefSize = textArea.getPreferredSize();
//        Dimension newPrefSize = new Dimension(oldPrefSize.width * 2, oldPrefSize.height);
//        textArea.setPreferredSize(newPrefSize);

        JPanel pane = new JPanel(new FlowLayout());
        pane.add(textArea);
        return pane;
    }

    protected JTextArea createTextArea() {
        JTextArea textArea = new JTextArea();
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);
        return textArea;
    }

}

采纳答案by Robin

Use the JTextArea#setColumnsmethod to adjust the width

使用JTextArea#setColumns方法调整宽度

回答by Ahmad Moussa

set linewrap to true => textArea.setLineWrap(true); this will make the maximum line width = textarea with

将换行设置为 true => textArea.setLineWrap(true); 这将使最大线宽 = textarea 与

回答by user3015208

Change this line of code textArea.setPreferredSize(newPrefSize); to textArea.setSize(newPrefSize); The height will be dynamically adjusted.

更改这行代码 textArea.setPreferredSize(newPrefSize); 到 textArea.setSize(newPrefSize); 高度将动态调整。