0

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);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Shahar Kazaz
  • 37
  • 1
  • 6
  • 5
    1) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space. 2) Don't set the size of top level containers. Instead layout the content & call `pack()`. 3) `textfield.setSize(150,20);` The size of a text filed is best hinted by the number of character it is meant to contain (supplied in the constructor) & the font. – Andrew Thompson Jun 17 '13 at 18:59
  • use setHorizontalTextPosition(javax.swing.LEFT); – voidMainReturn Jun 17 '13 at 19:09
  • and similarly setVerticalTextPosition(javax.swing.TOP) – voidMainReturn Jun 17 '13 at 19:10

1 Answers1

2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366