user2551736
user2551736

Reputation: 47

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);
    }

}

Upvotes: 0

Views: 104

Answers (2)

nachokk
nachokk

Reputation: 14413

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

Upvotes: 1

luke657
luke657

Reputation: 835

setBounds method works with only with null Layout and default JFrame's layout is BorderLayout. Invoking JFrame's add method with BorderLayout and without specifying location defaults to BorderLayout.CENTER and centers the component, using its maximum size property as bounds. That means that setting prefered size of the component won't work with BorderLayout.CENTER. You can either change the frame's layout to null, using setLayout(null), which is considered a bad practice, because it, among other things, limits portability of the code, or use other layout manager.

Upvotes: 1

Related Questions