Search code examples
javaswingawtlayout-managergridbaglayout

GridBagLayout align textField?


I want to shorten my text field so it doesn't stretch to to the end of my jframe so this is how it looks now: enter image description here

How do control the width of the textfield so it does't streatch like that I tried setPreferedSize() and setSize() yet they didn't work??

@Override
        public void run() {

            JFrame frame = new JFrame("Test Calculator");
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(500, 500);

            JPanel panel = new JPanel(new GridBagLayout());
            frame.getContentPane().add(panel, BorderLayout.NORTH);
            GridBagConstraints c = new GridBagConstraints();

            JLabel testLabel = new JLabel("Enter Score For Test 1: ");  
            c.gridx = 0;
            c.gridy = 0;
            c.anchor = GridBagConstraints.WEST;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new  Insets(40, 15, 15, 0);
            panel.add(testLabel , c);


            JTextField txtField1 = new JTextField("TextField");
            c.gridx = 1;
            c.gridy = 0;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = .5; 
            panel.add(txtField1 , c);
        }

Solution

  • You're telling the layout that the text field must fill horizontally, so that's what it does. Replace

    c.fill = GridBagConstraints.HORIZONTAL;
    

    by

    c.fill = GridBagConstraints.NONE;