Shahar Kazaz
Shahar Kazaz

Reputation: 37

JTextfield location won't change

I've been trying to set the location of my text field but it seems that it is only being generated the the middle of the JFrame.

I want it in the north left corner, how do I do that? I've add the code of my program.

     private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Atarim");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new Atarim(frame);
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.setLocationRelativeTo(null);
    frame.setSize(352, 950);
    JTextField textfield = new JTextField("search...");
    textfield.setLocation(0, 0);
    textfield.setSize(150,20);
    textfield.setVisible(true);
    newContentPane.add(textfield);
    frame.setVisible(true);
}

Upvotes: 0

Views: 919

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

The first thing I would do is try a get over this need for absolute control, it will make your life easier in the long run.

Swing employees a system know as layout managers to facilitate the positioning of UI elements on the screen. The layout manager API is fundamental to how Swing works. It makes developing UIs for different systems easier and quicker as you don't need to continuously calculate the difference in font metrics and screen resolutions for all the various systems that your UI may run on (having developed for both MacOS, Windows 7 and Windows XP simultaneously, I can ensure you this is a God send)

You could try something like...

newContentPane.setLayout(new GridBagLayout());
GridBagConstraintss gbc = new GridBagConstraintss();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
newContentPane.add(textfield);

Take a closer look at Using Layout !anagers and A visual guide to layout managers for more details

Upvotes: 2

Related Questions