Search code examples
javaswingjframejtextfieldlayout-manager

Placing JTextFields in a JFrame of a Java GUI


I have:

public class BaseStationFrame1 extends JFrame
{

    JButton activateButton;
    JButton deactivateButton;
    BaseStation bs;

    JTextField networkIdField;
    JTextField portField;



    public BaseStationFrame1(BaseStation _bs){

        bs = _bs;

        setTitle("Base Station");
        setSize(600,500); 
        setLocation(100,200);  
        setVisible(true);

        activateButton = new JButton("Activate");
        deactivateButton = new JButton("Deactivate");
        Container content = this.getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout()); 
        content.add(activateButton);
        content.add(deactivateButton);

        networkIdField = new JTextField("networkId : "+ bs.getNetworkId());
        networkIdField.setEditable(false);

        content.add(networkIdField);

        portField = new JTextField("portId : "+ bs.getPort());
        portField.setEditable(false);

        content.add(portField);}
    }

My problem is that i don't want the two TextFields to appear on the right of Activate and Deactivate buttons but below them. How can i fix that?


Solution

  • Specify your layout manager, like this:

    content.setLayout(new GridLayout(2,2));
    

    That would use the Grid Layout Manager to establish a grid with 2 columns and 2 rows, that your components would then be placed in.

    The layout manager you are currently using, FlowLayout, only adds contents onto the end of the current row. it will wrap around once it reaches the constrained edge of the pane, though. You should also check the other layout managers here

    You could alternatively use GridBagLayout , but you will have to specify a GridBagConstraints object you then add alongside the individual elements, like so:

    content.add(networkIdField, gridConstraints);
    

    see more on that in the linked tutorial.