Gorgochef
Gorgochef

Reputation: 89

Why Is My TextField Not Being The Size I Have Commanded It To Be?

I cannot figure out why my TextField is refusing to be the size I have demanded that it be. I was hoping to get some insight from you guys.

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.TextField;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class HW09 extends JFrame{

    public HW09() {
        this.setVisible(true);
        this.setSize(455, 155);


        TextField cartonsPerShipmentBox = new TextField("5");
        cartonsPerShipmentBox.setMaximumSize(new Dimension(20, 20));
        Button calculateButton = new Button("Calculate!");

        JPanel middleContainer = new JPanel();
        middleContainer.setLayout(new GridLayout(2, 4));
        middleContainer.add(new JLabel("Cartons Per Shipment: "));

        //CARTON AMOUNT
        middleContainer.add(cartonsPerShipmentBox);

        //TOTAL BOX
        middleContainer.add(new JLabel("Total: "));




        middleContainer.add(new JLabel("Items per carton: "));

        //ITEMS PER CARTON BOX
        middleContainer.add(new Button("OOF"));

        //CALCULATE BUTTON
        middleContainer.add(calculateButton);

        this.add(middleContainer);


    }

    public static void main(String[] args) {

        HW09 hw = new HW09();

    }

}

I want this because even though my items are in a grid layout, the TextField is really just too dang big for what I want and it makes the program look weird. I want the textfield to be pretty small, as I signified with the dimension(20, 20). However, when I run the program it makes the TextField the same size as every other item.

Upvotes: 0

Views: 40

Answers (2)

UVM
UVM

Reputation: 9914

That is how GridLayOut works in Swing. it will give equal width to all components in it. If you want more controlled behavior, then go for GridBagLayOut

You can check the following link:

Java change JTextField size inside a GridLayout

Upvotes: 1

Tarik Tutuncu
Tarik Tutuncu

Reputation: 818

The reason the width is not set to your preferred width is that the integer argument passed to the TextField constructor, 5 in the example, indicates the number of columns in the field. This number is used along with metrics provided by the field's current font to calculate the field's preferred width. It does not limit the number of characters the user can enter. To do that, you can either use a formatted text field or a document listener.

Try reducing the column width.

Upvotes: 2

Related Questions