Search code examples
javaswingjframejtextfield

JTextField in the whole JFrame instead of my determined Area


yes I'm a total beginner in Java... Could somebody tell me, why the JTextField is located in the whole JFrame instead of just the space between (300,50) to (450,75) like I've inputted in setBounds?

import java.awt.*;
import javax.swing.*;

public class Chat extends JFrame {

    JTextField t=new JTextField("");

    public Chat() {
        setVisible(true);
        setSize(900, 300);
        t = new JTextField();
        t.setBounds(300, 50, 150, 25);
        add(t);
    }

}

Solution

  • Cause the JFrame default layout is BorderLayout and when you add the components if you don't specify it will put in the center. I recommend to use another layout like GridBagLayout.

    Example:

    public Chat() {
          setSize(900, 300);
          t = new JTextField();
          t.setPreferredSize(new Dimension(x,y));
          GridBagConstraints gridBagConstraints = new GridBagConstraints();
          gridBagConstraints.gridx = 6;
          gridBagConstraints.gridy = 7;
          JPanel panel = new JPanel();
          panel.setLayout(new GridBagLayout());
          panel.add(t,gridBagConstraints);
          add(panel);
          pack(); // this sizes the frame
          setVisible(true); // call set visible after adding components
    }
    

    Should consider read this Using Layout Managers