Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

สร้าง Login Form ด้วย Java Swing

พัฒนา Login Form ด้วย Java Swing สร้าง 2 Label (username, password), 2 Text Field รับข้อมูล, 1 Submit Button ตรวจสอบข้อมูล ถ้าถูกต้องแสดง "Hello admin"

ตัวอย่างโค้ดเต็ม


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginDemo extends JFrame implements ActionListener {
    JPanel panel;
    JLabel user_label, password_label, message;
    JTextField userName_text;
    JPasswordField password_text;
    JButton submit, cancel;
    
    LoginDemo() {
        // Username
        user_label = new JLabel("User Name :");
        userName_text = new JTextField();
        
        // Password
        password_label = new JLabel("Password :");
        password_text = new JPasswordField();
        
        // Submit Button
        submit = new JButton("SUBMIT");
        panel = new JPanel(new GridLayout(3, 1));
        panel.add(user_label);
        panel.add(userName_text);
        panel.add(password_label);
        panel.add(password_text);
        message = new JLabel();
        panel.add(message);
        panel.add(submit);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        submit.addActionListener(this);
        add(panel, BorderLayout.CENTER);
        setTitle("Please Login Here !");
        setSize(450, 350);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new LoginDemo();
    }
    
    @Override
    public void actionPerformed(ActionEvent ae) {
        String userName = userName_text.getText();
        String password = password_text.getText();
        
        if (userName.trim().equals("admin") && password.trim().equals("admin")) {
            message.setText(" Hello " + userName + "");
        } else {
            message.setText(" Invalid user.. ");
        }
    }
}

คำอธิบายโค้ด

  • extends JFrame implements ActionListener
  • ใช้ GridLayout(3,1) จัดเรียง Label-Field คู่ๆ
  • JPasswordField สำหรับรหัสผ่าน (ซ่อนตัวอักษร)
  • ActionListener จัดการ event กดปุ่ม SUBMIT
  • ตรวจสอบ username/password = "admin"/"admin"

ปรับปรุงสำหรับ Production

  • ใช้ PreparedStatement ตรวจสอบกับ Database
  • Hash รหัสผ่านด้วย BCrypt/Argon2 ไม่เก็บ plain text
  • เพิ่ม Validation (empty check, length, format)
  • ใช้ JOptionPane แสดงผลแทน JLabel
  • Separate logic ออกจาก UI (MVC pattern)

ผลลัพธ์

หน้าต่าง Login มีช่อง Username, Password, ปุ่ม SUBMIT กรอก admin/admin → แสดง "Hello admin" ไม่ถูกต้อง → "Invalid user.."