使用绝对布局方式实现登录界面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014248473/article/details/88999663

一、写在前面

1. 使用绝对布局方式实现登录窗口;

2. 禁止窗口缩放与最大化;

二、代码

public class AbsoluteLoginFrame extends JFrame {
    private static final int LOGIN_WIDTH = 600;
    private static final int LOGIN_HEIGHT = 400;

    private static final long serialVersionUID = -2381351968820980500L;

    public AbsoluteLoginFrame(){
        //设置窗口标题
        setTitle("登录界面");

        //设置一个初始面板,填充整个窗口
        JPanel loginPanel = new JPanel();
        //设置背景颜色
        loginPanel.setBackground(new Color(204, 204, 204));//#CCC
        loginPanel.setLayout(null);

        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.WHITE);
        centerPanel.setBounds(114, 70, 360, 224);
        centerPanel.setLayout(null);

        JLabel jLabel = new JLabel("用户名:");
        jLabel.setOpaque(true);
        jLabel.setBackground(Color.YELLOW);
        jLabel.setBounds(60, 60, 54, 20);

        JLabel label = new JLabel("密    码:");
        label.setOpaque(true);
        label.setBackground(Color.CYAN);
        label.setBounds(60, 90, 54, 20);

        JTextField textField = new JTextField(15);
        textField.setBounds(130, 60, 166, 21);

        JPasswordField passwordField = new JPasswordField(15);
        passwordField.setBounds(130, 90, 166, 21);

        JButton jButton = new JButton("登录");
        jButton.setBounds(148, 120, 62, 28);

        centerPanel.add(jLabel);
        centerPanel.add(label);
        centerPanel.add(textField);
        centerPanel.add(jButton);
        centerPanel.add(passwordField);
        loginPanel.add(centerPanel);
        getContentPane().add(loginPanel);//将初始面板添加到窗口中

        setSize(LOGIN_WIDTH, LOGIN_HEIGHT);//设置窗口大小
        setLocation(Screen.getCenterPosition(LOGIN_WIDTH, LOGIN_HEIGHT));//设置窗口位置
        setDefaultCloseOperation(EXIT_ON_CLOSE);//设置窗口默认关闭方式
        setResizable(false);
        setVisible(true);
    }

    public static void main(String[] args) {
        new AbsoluteLoginFrame();
    }
}
public class Screen {

    private int width;
    private int height;

    public Screen(){
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        this.width = screenSize.width;
        this.height = screenSize.height;
    }

    public static Point getCenterPosition(int width, int height){
        Screen screen = new Screen();
        int x = (screen.getWidth() - width) / 2;
        int y = (screen.getHeight() - height) / 2;
        return new Point(x, y);
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}

 三、效果图

 

猜你喜欢

转载自blog.csdn.net/u014248473/article/details/88999663
今日推荐