通过JFrame构建登录界面
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
public static void main(String[] args) {
// 创建 JFrame 实例
JFrame frame = new JFrame("Login Example");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置界面为可关闭状态
JPanel panel = new JPanel();
// 添加面板
frame.add(panel);
doIt(panel);
// 设置界面可见
frame.setVisible(true);
}
private static void doIt(JPanel panel) {
panel.setLayout(null);
// 创建 JLabel
JLabel userLabel = new JLabel("User:");
/* 这个方法定义了组件的位置。
* setBounds(x, y, width, height)
* x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。
*/
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);
// 创建登录按钮
JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text=userText.getText();
String password=passwordText.getText();
System.out.println("账号:"+text);
System.out.println("密码:"+password);
}
});
//添加事件监听
panel.add(loginButton);
}
}
运行结果后,将通过事件监听器,将输入的账号密码打印到控制台界面中。
未来可以与数据库联用,将数据存储到数据库当中。