初学Java:Java基础-GUI图形用户界面(二)

Java基础 图形用户界面(二)

简单的登陆窗口

判断用户名及密码是否正确,点击登录按钮实现不同效果

代码

import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LoginFrame extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JPasswordField passwordField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    LoginFrame frame = new LoginFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LoginFrame() {
      //设置面板
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
				//创建、设置组件
        JLabel lblNewLabel = new JLabel("用户名");
        lblNewLabel.setBounds(95, 65, 61, 16);
        contentPane.add(lblNewLabel);

        JLabel label = new JLabel("密 码");
        label.setHorizontalAlignment(SwingConstants.LEFT);
        label.setBounds(95, 116, 41, 16);
        contentPane.add(label);

        textField = new JTextField();
        textField.setBounds(168, 60, 130, 26);
        contentPane.add(textField);
        textField.setColumns(10);

        passwordField = new JPasswordField();
        passwordField.setColumns(10);
        passwordField.setBounds(168, 111, 130, 26);
        contentPane.add(passwordField);

        JButton button = new JButton("登陆");
        button.setBounds(102, 175, 88, 29);
        contentPane.add(button);

        JButton button_1 = new JButton("退出");
      //按钮监测事件
        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);//退出
            }
        });
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String t1 = textField.getText();
                String t2 = String.valueOf(passwordField.getPassword());


                if (t1.equals("admin") && t2.equals("123456")){
                  JOptionPane.showMessageDialog(null,"登陆成功");
        }
              else {
                    JOptionPane.showMessageDialog(null,"用户名或密码错误");

                }

            }
        });
        button_1.setBounds(240, 175, 88, 29);
        contentPane.add(button_1);

    }
}

以上为本人学习Java时的一些笔记以及自己的理解

如有不足之处请大家指正

相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页