How can I control the width of JTextFields in Java Swing?

左心房为你撑大大i 提交于 2019-11-30 17:25:30

All Swing components have a preferred size. The preferred size of a text component is based on the text of the component. So generally the component is painted at its preferred size.

So I don't see the problem with your code snippet. Each text field should have a different preferred size. Also, as the frame is resized the width will be adjusted since the BoxLayout will try to resize each component up to its maximum/minimum size.

If you need more help post your SSCCE that actually demonstrates the sizing problem you are experiencing.

Edit:

Based on the latest requirement you can use the Relative Layout.

Michael Pankhurst
yourTextField = new JTextField("", 20);

if you start it like this it sets the textfield to be empty and to have 20 collumns

Try this:

textfield.setPreferredSize(new Dimension(int width, int height));
// 1. create JTextField
yourTextField = new JTextField();
// 2. store default height
int defaultHeight = yourTextField.getSize().getHeight();
// 3. set custom width and default height
yourTextField.setSize(new Dimension(yourWidth, defaultHeight));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!