1

I'm working on a GUI and i decided that I want to build the GUI with no layout. Instead, I'm using the setBounds() function. When I'm placing only one button it's all work fine, but when i place the other button, he's expanding and fills the hole screen.I can still click on the TextField but I can't see it (when I click on certain place it shows up). Here is my code:

//Graphical part
private JFrame loginFrame;
private JTextField userField;
private JButton send;
private JButton reg;
private JTextField passField;
public void graphics() {
    setRegister();
    int sizeX=120,sizeY=20,bSizeX=80,bSizeY=sizeY;
    int locationX=80,locationY=40;
    loginFrame=new JFrame("Login");
    loginFrame.setVisible(true);
    loginFrame.setSize(300,200);
    userField=new JTextField("");
    passField=new JTextField("");
    loginFrame.add(userField);
    loginFrame.add(passField);
    userField.setBounds(locationX, locationY, sizeX, sizeY);
    passField.setBounds(locationX, locationY+10+sizeY, sizeX, sizeY);
    send=new JButton("Send");
    send.addActionListener(this);
    loginFrame.add(send);
    send.setBounds(locationX+40,10+2*(locationY+10), bSizeX, bSizeY);
    reg=new JButton("Register");
    reg.setBounds(0, 0, bSizeX, bSizeY);
    loginFrame.add(reg);
    //reg.addActionListener(this);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2129468
  • 681
  • 3
  • 8
  • 12
  • 3
    The mistake is not using layout managers with a framework designed to be used with them. The components have default layout managers which results in a conflict when you do not take that in account. Really, the only reason to use absolute placement is teaching oneself what a grand mistake it is. – kiheru Aug 18 '13 at 10:17
  • Always make calls like `pack()/setVisible()` at the end, once you are done adding components to the container, this way it realizes it's size in a better way. – nIcE cOw Aug 18 '13 at 10:45

1 Answers1

3

By default JFrames have BorderLayout as layout manager, so your code really does use it. If you want to test your code without layout, you need to specify it as null:

 loginFrame.setLayout(null);
Igor Rodriguez
  • 1,196
  • 11
  • 16
  • 2
    +1, fo specifying the need to call `setLayout(null)`. Though do specify the OP, to read the first paragraph of [Absolute Positioning](http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html), which clears the reason, as to why this approach is discouraged :-) – nIcE cOw Aug 18 '13 at 10:43