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

后端 未结 5 1468
天涯浪人
天涯浪人 2020-12-31 00:17

I have a JPanel that looks something like this:

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

...

pane         


        
相关标签:
5条回答
  • 2020-12-31 00:56
    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);
    
    0 讨论(0)
  • 2020-12-31 01:07

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

    0 讨论(0)
  • 2020-12-31 01:13

    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());
    
    0 讨论(0)
  • 2020-12-31 01:19
    textField = new JTextField( ... );
    textField.setMaximumSize( textField.getPreferredSize() );
    
    0 讨论(0)
  • 2020-12-31 01:19

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

    0 讨论(0)
提交回复
热议问题