简体   繁体   English

如何阻止wordwrapped-JTextArea调整大小以适应大内容?

[英]How to stop wordwrapped-JTextArea from resizing to fit large content?

I currently have a wordwrapped-JTextArea as a user input window for a chat program. 我目前有一个wordwrapped-JTextArea作为聊天程序的用户输入窗口。 How do I make it so the JTextArea doesn't resize to automatically fit large text? 如何使JTextArea不调整大小以自动适合大文本? I have already set the JTextArea to be 2 rows: 我已经将JTextArea设置为2行:

user_input = new JTextArea();
user_input.addAncestorListener(new RequestFocusListener());
user_input.setRows(2);
user_input.setLineWrap(true);
user_input.setWrapStyleWord(true);

You should put your JTextArea in a JScrollPane . 您应该将JTextArea放在JScrollPane This will keep your row size intact, and would have the added benefit of allowing the user to navigate the input. 这将保持行大小不变,并且具有允许用户导航输入的额外好处。 If you want, you can set the scrollpane to never show. 如果需要,可以将滚动窗格设置为从不显示。 You can still rely on the JTextArea component to calculate the height of the rows and then the preferred height of the component. 您仍然可以依赖JTextArea组件来计算行的高度,然后计算组件的首选高度。

The call to setRows that you use to indicate the amount of rows visible on your display is a property that is maintained to work with JScrollPane , as described in the JTextArea JavaDoc : 对用于指示显示器上可见行数的setRows的调用是一个可以与JScrollPane一起使用的属性,如JTextArea JavaDoc中所述

java.awt.TextArea has two properties rows* and columns that are used to determine the preferred size. java.awt.TextArea有两个属性行*和列,用于确定首选大小。 JTextArea uses these properties to indicate the preferred size of the viewport when placed inside a JScrollPane to match the functionality provided by java.awt.TextArea. 当放置在JScrollPane中以匹配java.awt.TextArea提供的功能时,JTextArea使用这些属性来指示视口的首选大小。 JTextArea has a preferred size of what is needed to display all of the text, so that it functions properly inside of a JScrollPane. JTextArea具有显示所有文本所需的大小,因此它在JScrollPane内部正常运行。

*my emphasis *我的重点

使用setPreferredSize(new Dimension(...))以便JTextArea保留您设置的维度。

It's a function of the layout manager you're using, but you can try to force it by setting setPreferredSize() and setMaximusSize() on your text area. 它是您正在使用的布局管理器的一个功能,但您可以尝试通过在文本区域设置setPreferredSize()setMaximusSize()来强制它。

See the docs for JComponent . 请参阅JComponent的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM