Java 如何将 JTextArea 设置为固定大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22914775/
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-08-13 18:55:42  来源:igfitidea点击:

How to set JTextArea to fixed size

javaswingjtextarea

提问by Aviv Cohn

I have a JTextArea inside a JPanel. The JPanel is set to the default FlowLayout.

我在 JPanel 中有一个 JTextArea。JPanel 设置为默认 FlowLayout。

I assigned to the JTextArea a size through the constructor: new JTextArea(50,50).

我分配到的JTextArea大小通过构造函数:new JTextArea(50,50)

However, not only the size I specified is ignored once it's out of a certain range (for example, if I set the size to a value larger than 40*40, the program starts to ignore what I say and instead set the JTextArea to some arbitrary size) - the size also changes as I type. The JTextArea resizes itself if I type inside it more than it can contain.

但是,不仅我指定的大小在超出某个范围时会被忽略(例如,如果我将大小设置为大于 40*40 的值,则程序开始忽略我所说的内容,而是将 JTextArea 设置为某个值任意大小) - 大小也会随着我的输入而改变。如果我在 JTextArea 中键入的内容超出其所能包含的范围,则 JTextArea 会自行调整大小。

I did:

我做了:

textArea.setLineWrap(true);

textArea.setLineWrap(true);

Didn't solve this.

没有解决这个问题。

How can I set a fixed size for the JTextArea?

如何为 JTextArea 设置固定大小?

采纳答案by BaptisteL

If you include it in a JScrollPane that might solve your problem :

如果您将其包含在可能解决您的问题的 JScrollPane 中:

JTextArea textArea = new JTextArea(50, 50);
JScrollPane scrollPane = new JScrollPane( textArea );

You might also have to change you Layout, because by default I think it use the BorderLayoutthat expands your components. Or put it in PAGE_STARTlike this :

您可能还需要更改布局,因为默认情况下我认为它使用BorderLayout扩展组件的 。或者PAGE_START像这样输入:

add(new JScrollPane(new JTextArea(50, 50)), BorderLayout.PAGE_START);

回答by agilob

If you want to have fixed size, you have to put it inside a box like JScrollPane:

如果你想有固定的大小,你必须把它放在一个像 JScrollPane 这样的盒子里:

JScrollPane jsp = new JScrollPane(textarea);

if you want the text area to fit maximum number of letters:

如果您希望文本区域适合最大数量的字母:

textarea.setColumns(100); 

回答by Arrem

Try using textArea.setPreferredSize(new Dimension(WIDTH, HEIGHT));

尝试使用 textArea.setPreferredSize(new Dimension(WIDTH, HEIGHT));