- 创建项目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6577c005a4c9bc566b696523d25592b5.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/332b21c24671476618211736be5b01d9.gif)
- 编写代码,本地调试
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fa11220692622f832e620c1e50fc5aaa.png)
package com.xicheng.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Example");
frame.setSize(360, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("User: ");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
JLabel loginInfoLabel = new JLabel();
loginInfoLabel.setBounds(90, 120, 180 ,25);
loginInfoLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(loginInfoLabel);
JButton loginButton = new JButton("login");
loginButton.setBounds(140, 80, 80, 25);
loginButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String user = userText.getText();
String password = passwordText.getText();
boolean result = login(user, password);
if (result) {
loginInfoLabel.setText("登录成功~");
} else {
loginInfoLabel.setForeground(Color.RED);
loginInfoLabel.setText("用户名或密码不对");
}
}
});
panel.add(loginButton);
}
private static boolean login(String user, String password) {
return "admin".equalsIgnoreCase(user) && "123456".equals(password);
}
}
- 生成可执行jar包并运行
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/81fafedd2ebc9007f74d5a53582cc464.gif)