一.界面
二.代码
package test08_Login;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
LoginGUI loginGUI = new LoginGUI();
}
}
class LoginGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JLabel jlabel1, jlabel2;
JTextField usernameText;
JPasswordField passwordText;
JButton loginButton, cancelButton;
JPanel jpanel1, jpanel2, jpanel3;
public LoginGUI() {
jpanel1 = new JPanel();
jpanel2 = new JPanel();
jpanel3 = new JPanel();
jlabel1 = new JLabel("用户名");
jlabel2 = new JLabel("密 码");
usernameText = new JTextField(10);
passwordText = new JPasswordField(10);
loginButton = new JButton("登录");
cancelButton = new JButton("取消");
Font font = new Font("楷体", Font.BOLD, 18);
jlabel1.setFont(font);
jlabel2.setFont(font);
loginButton.setFont(font);
cancelButton.setFont(font);
Color color = new Color(0, 0, 255);
jlabel1.setForeground(color);
jlabel2.setForeground(color);
loginButton.setForeground(color);
cancelButton.setForeground(color);
this.setLayout(new GridLayout(3, 1, 5, 5));
jpanel1.add(jlabel1);
jpanel1.add(usernameText);
jpanel2.add(jlabel2);
jpanel2.add(passwordText);
jpanel3.add(loginButton);
jpanel3.add(cancelButton);
this.add(jpanel1);
this.add(jpanel2);
this.add(jpanel3);
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
ImageIcon icon = new ImageIcon("./src/test08_Login/qq.png");
this.setIconImage(icon.getImage());
this.setTitle("用户登录");
this.setSize(300, 180);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setLocation(width / 2 - 200, height / 2 - 150);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
if (checkPassword() == true) {
JOptionPane.showMessageDialog(null, "用户名和密码正确,欢迎登录!", "提示", 1);
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误,请重新登录!", "提示", 2);
}
} else {
if (e.getActionCommand() == "取消") {
clearText();
}
}
}
public boolean checkPassword() {
String userName = "dxxy";
String password = "admin";
String inputUserName = usernameText.getText().trim();
String inputPassword = String.valueOf(passwordText.getPassword()).trim();
if (userName.equals(inputUserName) && password.equals(inputPassword)) {
return true;
} else {
return false;
}
}
public void clearText() {
usernameText.setText("");
passwordText.setText("");
}
}