如何在 Java 中设置文本字段的高度和宽度?

问题描述:

我试图让 JTextField 填充宽度并为其设置高度,但仍然失败.我尝试添加代码 setPreferredSize(new Dimension(320,200)); 但仍然失败.有什么办法可以让我的 JTextField 填充宽度并将高度设置为 200 之类的吗?

I was trying to make my JTextField fill the width and set a height for it but still failed. I tried adding the code setPreferredSize(new Dimension(320,200)); but still failed. Is there any way I can make my JTextField fill the width and set the height to 200 or something?

你不应该玩弄高度.让文本字段根据使用的字体确定高度.

You should not play with the height. Let the text field determine the height based on the font used.

如果你想控制文本框的宽度那么你可以使用

If you want to control the width of the text field then you can use

textField.setColumns(...);

让文本字段决定首选宽度.

to let the text field determine the preferred width.

或者如果您希望宽度是父面板的整个宽度,那么您需要使用适当的布局.也许是 BorderLayout 的北边.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

有关详细信息,请参阅关于布局管理器的 Swing 教程.

See the Swing tutorial on Layout Managers for more information.