| 問題 | 原因 | 修復 |
|---|---|---|
| main 中 frame 為非 static | 靜態方法無法訪問非靜態字段 | `private static JFrame frame = new JFrame(...);` |
| 缺少 JOptionPane 匯入 | 編譯器未報錯但運行時找不到類 | `import javax.swing.JOptionPane;` |
| `JPasswordField.getPassword()` 返回 `char[]`,直接賦值給 `String` 導致編譯錯誤/邏輯錯誤 | 類型不匹配,`==` 比較的是引用而非內容 | `String psw1 = String.valueOf(password.getPassword());` `String psw2 = String.valueOf(password2.getPassword());` |
| 字符串比較用 `==` | 比較引用地址,應用 `equals()` | `if (psw1.equals(psw2))` |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WinReg implements ActionListener {
private static JFrame frame = new JFrame("Register");
private JTextField username = new JTextField();
private JPasswordField password = new JPasswordField();
private JPasswordField password2 = new JPasswordField();
private JButton confirm = new JButton("Confirm");
private JButton cancel = new JButton("Cancel");
public WinReg() {
frame.setSize(600, 400);
frame.setLayout(new BorderLayout());
initFrame();
confirm.addActionListener(this);
cancel.addActionListener(this);
frame.setVisible(true);
}
private void initFrame() { /* 界面佈局代碼省略 */ }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(frame, "Alert", "Alert", JOptionPane.ERROR_MESSAGE);
new WinReg();
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == confirm) {
String usn = username.getText();
String psw1 = String.valueOf(password.getPassword());
String psw2 = String.valueOf(password2.getPassword());
if (psw1.equals(psw2)) {
JOptionPane.showMessageDialog(frame, "Passwords match!");
System.out.println(psw1);
} else {
JOptionPane.showMessageDialog(frame, "Passwords do not match!");
}
}
}
}
修復以上問題後,註冊對話框的密碼驗證與彈窗提示均能正常工作。