javaswingjtextfieldpreferredsize

Setting the preferred size of a JTextFieldis not working


I'm trying to set the size of JTextField, but for some reason it stays the same size and fills up the whole JPanel, I am using setPreferredSize, but this makes no difference:

JPanel loginJPanel = new JPanel(new BorderLayout());
JTextField usernameJTextField = new JTextField();
usernameJTextField.setPreferredSize(new Dimension(50, 100));
loginJPanel.add(usernameJTextField);

Solution

  • It does make a difference, but the layout may choose to ignore preferred size settings. The center area of BorderLayout gets as much of the available space as possible. See How to Use BorderLayout for more details.

    Consider this example that packs the frame, as a result the preferred size of the text field is respected. But once the frame is resized, the text field is resized as well.

    import javax.swing.*;
    import java.awt.*;
    
    class Demo {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JPanel loginJPanel = new JPanel(new BorderLayout());
                    JTextField usernameJTextField = new JTextField();
                    usernameJTextField.setPreferredSize(new Dimension(50, 100));
                    loginJPanel.add(usernameJTextField);
    
                    JFrame frame = new JFrame();
                    frame.add(loginJPanel);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                    frame.pack();
                    frame.setLocationByPlatform(true);
                    frame.setVisible(true);
                }
            });
        }
    }
    

    Take a look at Visual Guide to Layout Managers and perhaps you would find a more suitable layout for your needs.

    Also, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?.

    EDIT:

    Note that you're usually encouraged to specify the number of columns when initializing text fields. This number is used to calculate preferred width. For example textField = new JTextField(20); See How to Use Text Fields for more details:

    If you do not specify the number of columns or a preferred size, then the field's preferred size changes whenever the text changes, which can result in unwanted layout updates.