Why wont my component centre correctly when using correct numbers?

No One Knows :

I am writing a small login program, and am wondering why my Button won't centre into the middle of the screen. It looks slightly too far to the right, but the numbers i used would suggest it should be directly in the middle, with equal free space on either side of it. There is more free space on the left of it than on the right. Any help is much appreciated, Thanks.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Login extends JFrame
{
    int width = 600;
    int height = 900;

    JButton usernameTF = new JButton();

    void makeFrame()
    {
        this.setTitle("Login");
        this.setSize(width,height);
        this.setLocation(0,0);
        this.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.getContentPane().setBackground(new java.awt.Color(140, 156, 144));

        makeComponents();

        this.setVisible(true);
    }

    void makeComponents()
    {
        usernameTF.setBounds(150,150,300,75);
        this.add(usernameTF);
    }

    public static void main(String[] args)
    {
        Login l = new Login();
        l.makeFrame();
    }
}
camickr :

wondering why my Button won't centre into the middle of the screen.

The frame size include the borders and title bar. You did not take those sizes into account when you tried to position the component.

Don't use a null layout!

Swing was designed to be used with layout managers. A layout manager will allow the component to be dynamically repositioned as the frame size changes or as the button size changes.

The easiest way to do what you want is to use the GridBagLayout.

//this.setLayout(null);
setlayout( new GridBagLayout() );

and

//usernameTF.setBounds(150,150,300,75);
//this.add(usernameTF);
usernameTF.setPreferredSize( new Dimension(300, 75) );
add(usernameTF, new GridBagConstraints());

The default constraint will cause the component to be centered in the space available. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18604&siteId=1