Syed Talal Jilani
Syed Talal Jilani

Reputation: 13

setBounds is not working on TextField in Java

I want to add two text fields in the panel. The layout of the panel is a Grid Layout. I add setBounds for the height and width of the text field but setBounds is not working properly. This is my code...

  import java.awt.*;
  import javax.swing.*;
  class gui1
    {
        public static void main(String[] args)
        {
            JFrame frm = new JFrame();
            JPanel pan = new JPanel();
            Button btn = new Button("SUBMIT");
            
            TextField txt1 = new TextField();
            TextField txt2 = new TextField();
            Label lbl = new Label("LOGIN FORM");
            
            txt1.setBounds(20,20,100,200);
            txt2.setBounds(20,20,200,300);
            frm.setLayout(new BorderLayout());
            pan.setLayout(new GridLayout(1,2));
            pan.add(txt1);
            pan.add(txt2);
            frm.add(pan,BorderLayout.CENTER);
            frm.add(lbl,BorderLayout.NORTH);
            frm.setSize(800,500);
            
            frm.setVisible(true);
            frm.setDefaultCloseOperation(frm.EXIT_ON_CLOSE);
       }
    }

Upvotes: 0

Views: 723

Answers (1)

Ryan
Ryan

Reputation: 1760

The layout manager will reset or ignore manually set values depending on the manager. Don't set UI bounds/size manually. We have layout managers for a reason; use them. As a general rule, if you're putting layouts inside of other layouts, you're doing it wrong. You can likely do what you want by using a different manager. I would suggest using GridBagLayout. It's a little more complicated to use, but you'll get better results in the long run.

Upvotes: 1

Related Questions