用java 图形用户界面编写一个页面,有两个按钮,一个是教师进入,一个是学生进入,进入后要输入ID和密码,在D盘中有文本文档内放ID和密码,进行判断是否正确,错误返回初始界面,正确进入下一界面,先为空白界面,要完整代码
时间: 2024-12-24 19:20:24 浏览: 5
在Java中创建一个图形用户界面(GUI)应用程序,可以使用Swing或JavaFX库。这里是一个简单的示例,使用Swing框架来实现这个需求。首先确保已导入所需的Swing库:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LoginWindow extends JFrame {
private JTextField idField;
private JPasswordField passwordField;
private JButton teacherButton;
private JButton studentButton;
private String documentPath = "D:\\ids_and_passwords.txt";
public LoginWindow() {
// 初始化窗口和组件
setTitle("Login");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
idField = new JTextField();
JLabel passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField();
teacherButton = new JButton("Teacher");
studentButton = new JButton("Student");
panel.add(idLabel);
panel.add(idField);
panel.add(passwordLabel);
panel.add(passwordField);
teacherButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
checkCredentials("teacher");
}
});
studentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
checkCredentials("student");
}
});
add(panel);
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
private void checkCredentials(String userType) {
if (isCredentialValid(userType)) {
// 如果验证通过,跳转到下一个界面
// 这里只是一个简单示例,实际应用中你可以创建一个新的Frame或者CardLayout来切换界面
JOptionPane.showMessageDialog(rootPane, "Credentials verified! Proceed to next interface.");
} else {
JOptionPane.showMessageDialog(rootPane, "Invalid credentials. Please try again.");
}
}
private boolean isCredentialValid(String userType) {
try (BufferedReader reader = new BufferedReader(new FileReader(documentPath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] details = line.split(",");
if (details.length == 2 && userType.equals(details[0])) {
return userMatchesPassword(userType, details[1], getPassword());
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return false;
}
private boolean userMatchesPassword(String userType, String expectedPassword, char[] enteredPassword) {
// 这里只是一个基本的比较,实际情况应更安全地处理密码
return userType.equals(expectedPassword) || enteredPassword.equals(passwordField.getPassword());
}
private char[] getPassword() {
return passwordField.getPassword();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LoginWindow();
}
});
}
}
```
这是一个基本的登录窗口,当点击“教师”或“学生”按钮时会尝试读取文件中的信息进行验证。注意这只是一个简化的例子,实际应用中需要处理更多边界情况,并提供更好的用户体验。
阅读全文