How do I keep JTextFields in a Java Swing BoxLayout from expanding?

自作多情 提交于 2019-11-30 08:09:23
textField = new JTextField( ... );
textField.setMaximumSize( textField.getPreferredSize() );

If you want the width to keep changing, just keep it set to MAX INT. So...

textField.setMaximumSize( 
     new Dimension(Integer.MAX_VALUE, textField.getPreferredSize().height) );

In my case I need a combination of all the answers for it to work properly. If I don't use glue, it is not centered vertically; if I don't restrict maximum size, it extends vertically; if I restrict both width and height, it is too small, being only wide enough to contain the initialization text.

textField = new JTextField("Hello, world!");
textField.setMaximumSize(
    new Dimension(Integer.MAX_VALUE,
    textField.getPreferredSize().height));
Box box = Box.createVerticalBox();
box.add(Box.createVerticalGlue());
box.add(textField);
box.add(Box.createVerticalGlue());

set the max height. or put them in a scroll region

Zhang Yujiao
JPanel panel = new JPanel();

Box box = Box.createVerticalBox();

JTextField tf = new JTextField(8);

box.add(tf);
panel.add(box);

frame.getContentPane().add(panel, BorderLayout.CENTER);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!