OiRc
OiRc

Reputation: 1622

Java Frame Layout

I have to make a login interface.I tried to use the border layout instead of using this model for the frame, but when I go to write setLocationRelativeTo (null), the internal components of the frame are displayed wrong. Some tips for how to set the frame at the center of the screen and the internal components at the center of the screen and displayed well and in specific coordinates?

class Login extends JFrame {
        JLabel label1;
        final JTextField text1;
        public Login(){
        setTitle("title");
        setLayout(null); //output on left-corner of screen or
       setLocationRelativeTo(null); // output on the middle with components displayed wrong
        label1 = new JLabel();
        label1.setText("text");
        text1 = new JTextField(15);
        label1.setBounds(100, 100, 100, 20);
        text1.setBounds(200, 100, 200, 20);
        add(label1);
        add(text1);
        setVisible(true);
        setSize(500, 400);

}public static void main(string [] args){ ` . . . . . .

new Login();}

Upvotes: 1

Views: 285

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your immediate problem can be solved by calling setLocationRelativeTo(null); after calling setSize(...)

  setSize(500, 400);
  setLocationRelativeTo(null);

But having said that, my actual recommendations are:

  • Don't call setSize(...). Let the layout managers do this for you.
  • Do use layout managers.
  • Do call pack() before setVisible(true)
  • Do call setLocationRelativeTo(null); after pack and before setVisible if you want to center the GUI.
  • Do learn to create a minimal, compilable, runnable example when asking similar questions. Your current code does not follow the rules of this simple tool, forcing us to do this for you.

Upvotes: 2

Related Questions