如何防止 Java Swing BoxLayout 中的 JTextFields 扩展?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2709220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I keep JTextFields in a Java Swing BoxLayout from expanding?
提问by Matthew
I have a JPanel
that looks something like this:
我有一个JPanel
看起来像这样的:
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 JTextField
s 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).
我的问题是JTextField
s 在垂直方向上变得很大。我希望它们只对一行来说足够高,因为这是用户可以输入的全部内容。按钮很好(它们不会垂直扩展)。
Is there any way to keep the JTextField
s from expanding? I'm pretty new to Swing, so let me know if I'm doing everything horribly wrong.
有什么办法可以防止JTextField
s 扩大?我是 Swing 的新手,所以如果我做的一切都非常错误,请告诉我。
采纳答案by camickr
textField = new JTextField( ... );
textField.setMaximumSize( textField.getPreferredSize() );
回答by Randy
set the max height. or put them in a scroll region
设置最大高度。或将它们放在滚动区域
回答by cbrown
If you want the width to keep changing, just keep it set to MAX INT. So...
如果您希望宽度不断变化,只需将其设置为 MAX INT。所以...
textField.setMaximumSize( new Dimension(Integer.MAX_VALUE, textField.getPreferredSize().height) );
回答by 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);
回答by damix911
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());