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

徘徊边缘 提交于 2019-11-29 11:08:14

问题


I have a JPanel that looks something like this:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

...

panel.add(jTextField1);
panel.add(Box.createVerticalStrut(10));
panel.add(jButton1);

panel.add(Box.createVerticalStrut(30));

panel.add(jTextField2);
panel.add(Box.createVerticalStrut(10));
panel.add(jButton2);

... //etc.

My problem is that the JTextFields become huge vertically. I want them to only be high enough for a single line, since that is all that the user can type in them. The buttons are fine (they don't expand vertically).

Is there any way to keep the JTextFields from expanding? I'm pretty new to Swing, so let me know if I'm doing everything horribly wrong.


回答1:


textField = new JTextField( ... );
textField.setMaximumSize( textField.getPreferredSize() );



回答2:


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) );



回答3:


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());



回答4:


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




回答5:


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);


来源:https://stackoverflow.com/questions/2709220/how-do-i-keep-jtextfields-in-a-java-swing-boxlayout-from-expanding

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