ndjffn
ndjffn
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.HashMap;
public LoginFrame() {
setTitle("用户登录");
setSize(350, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
loadUsers();
panel.add(inputPanel);
panel.add(loginBtn);
panel.add(registerBtn);
add(panel);
}
@SuppressWarnings("unchecked")
private void loadUsers() {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("users.dat"))) {
users = (HashMap<String, String>) ois.readObject();
} catch (FileNotFoundException e) {
users = new HashMap<>();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public RegisterFrame() {
setTitle("用户注册");
setSize(350, 300);
setLocationRelativeTo(null);
loadUsers();
panel.add(inputPanel);
panel.add(registerBtn);
panel.add(backBtn);
add(panel);
}
if (username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(this, "用户名和密码不能为空!");
return;
}
if (!password.equals(confirm)) {
JOptionPane.showMessageDialog(this, "两次输入的密码不一致!");
return;
}
if (users.containsKey(username)) {
JOptionPane.showMessageDialog(this, "用户名已存在!");
} else {
users.put(username, password);
saveUsers();
JOptionPane.showMessageDialog(this, "注册成功!");
new LoginFrame().setVisible(true);
dispose();
}
}
@SuppressWarnings("unchecked")
private void loadUsers() {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("users.dat"))) {
users = (HashMap<String, String>) ois.readObject();
} catch (FileNotFoundException e) {
users = new HashMap<>();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
panel.add(voteBtn);
panel.add(statsBtn);
add(panel);
}
}
public VoteFrame() {
setTitle("投票界面");
setSize(300, 150);
setLocationRelativeTo(null);
loadVotes();
submitBtn.addActionListener(e -> {
String candidate = (String) candidateBox.getSelectedItem();
votes.put(candidate, votes.getOrDefault(candidate, 0) + 1);
saveVotes();
JOptionPane.showMessageDialog(this, "投票成功!");
dispose();
});
panel.add(candidateBox, BorderLayout.CENTER);
panel.add(submitBtn, BorderLayout.SOUTH);
add(panel);
}
@SuppressWarnings("unchecked")
private void loadVotes() {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("votes.dat"))) {
votes = (HashMap<String, Integer>) ois.readObject();
} catch (FileNotFoundException e) {
initializeVotes();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
add(new JScrollPane(textArea));
}
}
```
代码说明:
使用说明:
1. 首次运行会自动创建数据文件
2. 需要先注册用户才能登录
3. 投票结果会自动保存并在统计界面显示
4. 候选人名单硬编码为三个候选人,可根据需要修改