搜尋
首頁Javajava教程java如何實作登入視窗

java如何實作登入視窗

Apr 19, 2023 pm 11:31 PM
java

登入視窗主類別

package ccnu.paint;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import ccnu.util.Answer;
import ccnu.util.Verification;

public class Login extends JFrame
{
    private static final long serialVersionUID = 1L;

    private Properties pro = new Properties();

    private boolean ver_code = false; // 默认输入验证码错误

    private Answer answer = null;

    private JPanel p1 = new JPanel(); // 添加到JPanel中的组件默认为流式布局
    private JLabel luser = new JLabel("username: ");
    private JTextField username = new JTextField(20);

    private JPanel p2 = new JPanel();
    private JLabel lpwd = new JLabel("password: ");
    private JPasswordField pwd = new JPasswordField(20);

    private JPanel p4 = new JPanel();
    private JLabel lVer = new JLabel("verification: ");
    private JTextField ver = new JTextField(10);
    private JLabel img = new JLabel();
    private JLabel result = new JLabel();

    private JPanel p3 = new JPanel();
    private JButton ok = new JButton("ok");
    private JButton cancel = new JButton("cancel");
    private JButton signUp = new JButton("Sign up"); // 用于账户注册

    // 设置组件的监听
    public void initListener()
    {
        username.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {// JTextField的action是回车键
                String name = username.getText();
                // Login.this.setTitle(name);
                // System.out.println(name.hashCode() + "***" +"".hashCode());
                if (name.equals(""))
                {
                    JOptionPane.showMessageDialog(Login.this, "Please input a userName!");
                } else
                {
                    pwd.grabFocus();
                }
            }
        });

        pwd.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                String password = new String(pwd.getPassword());
                if(password.equalsIgnoreCase(""))
                {
                    JOptionPane.showMessageDialog(Login.this, "please input a password!");
                }else{
                    ver.grabFocus();
                }
            }

        });

        ok.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e)
            {
                // 重新加载最新的账户文件
                try
                {
                    pro.load(new FileInputStream(new File("src/res/accouts.properties")));
                } catch (IOException e1)
                {
                    e1.printStackTrace();
                }
                check();
            }

        });

        // 判断验证码是否正确
        ver.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                String verCode = ver.getText();
                if(verCode.equals(""))
                {
                    JOptionPane.showMessageDialog(Login.this, "Please input a verification!");
                }else{
                    if(verCode.equals(answer.getResult()))
                    {
                        result.setIcon(new ImageIcon(Login.this.getClass().getResource("/res/right.jpg"))); // 显示提示的图片信息(如√图片)
                        ver_code = true;
                        // 检查之前,重新加载最新的账户文件
                        try
                        {
                            pro.load(new FileInputStream(new File("src/res/accouts.properties"))); // 将账户文件加载进来
                        } catch (IOException e1)
                        {
                            e1.printStackTrace();
                        }
                        check();
                    }else{
                        result.setIcon(new ImageIcon(Login.this.getClass().getResource("/res/error.jpg"))); // 显示提示的图片信息(如×图片) 
                        ver_code = false;
                    }
                }
            }
        });

        // 点击图片会更改验证码
        img.addMouseListener(new MouseAdapter(){

            @Override
            public void mouseClicked(MouseEvent e)
            {
                answer = Verification.verification();
                img.setIcon(new ImageIcon(answer.getBufferedImage())); // 设置验证码图案
            }
        });

        cancel.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int option = JOptionPane.showConfirmDialog(Login.this, "Are you sure to exit?");
//              System.out.println("option = " + option);
                if (option == 0)
                {// Yes
                    Login.this.dispose();
                }
            }
        });

        signUp.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e)
            {
                new SignUp();
            }
        });
    }

    // 初始化登录窗口及其组件的设置监听
    public Login()
    {
        super("Login");

        // 加载账户文件
        try
        {
            pro.load(new FileInputStream(new File("src/res/accouts.properties"))); // 从指定位置将账户文件加载进来
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        initListener();
        answer = Verification.verification(); // 生成验证码
        img.setIcon(new ImageIcon(answer.getBufferedImage())); // 设置初始验证码

        this.setLocation(new Point(200, 200));
        this.setSize(500, 300);
        this.setLayout(new GridLayout(4, 1, 0, 20)); // 垂直间隙为20px
        p1.add(luser);
        p1.add(username);
        p2.add(lpwd);
        p2.add(pwd);
        p4.add(this.lVer);
        p4.add(this.ver);
        p4.add(this.img);
        result.setForeground(Color.red);
        result.setFont(new Font("楷体", Font.BOLD, 20));
        p4.add(result);
        p3.add(ok);
        p3.add(cancel);
        p3.add(signUp);
        this.add(p1);
        this.add(p2);
            this.add(p4);
        this.add(p3);

//      this.setBackground(Color.blue); // JFrame的上层还有一个ContentPane
        this.getContentPane().setBackground(Color.gray);
        this.setResizable(false);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 等价于Frame中的windowClosing事件
    }

    // 检查用户名或密码
    public void check()
    {

        String verCode = ver.getText();
        if(verCode.equals(""))
        {
            JOptionPane.showMessageDialog(Login.this, "Please input a verification!");
            return;
        }else{
            if(verCode.equals(answer.getResult()))
            {
                result.setIcon(new ImageIcon(Login.this.getClass().getResource("/res/right.jpg")));
                ver_code = true;
            }else{
                result.setIcon(new ImageIcon(Login.this.getClass().getResource("/res/error.jpg")));
                ver_code = false;
            }
        }

        if(ver_code == false)
        {
            JOptionPane.showMessageDialog(this, "verification is error!");
            return;
        }
        String name = username.getText();
        String password = new String(pwd.getPassword()); // return char[]
//      if (name.equalsIgnoreCase("admin") && password.equals("123456"))
        if (isPass(name, password))
        {
//          new PaintApp(name);
            JOptionPane.showMessageDialog(this, "-^_^-   OK..."); // 此处可以加上其他的登陆成功后进一步处理的窗口
            this.dispose();
        } else
        {
            JOptionPane.showMessageDialog(this, "userName or password is incorrect!");
            username.setText("");
            pwd.setText("");
            ver.setText("");
            answer = Verification.verification();
            img.setIcon(new ImageIcon(answer.getBufferedImage()));
            result.setIcon(null);
        }
    }

    // 验证用户输入的账户名和密码是否正确(通过与加载进来的账户 pro 比对)
    public boolean isPass(String name, String password)
    {
        Enumeration en = pro.propertyNames();
        while(en.hasMoreElements())
        {
            String curName = (String)en.nextElement();
//          System.out.println(curName + "---" + pro.getProperty(curName));
            if(curName.equalsIgnoreCase(name))
            {
                if(password.equalsIgnoreCase(pro.getProperty(curName)))
                {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args)
    {
        new Login();
    }
}

帳號註冊類別

package ccnu.paint;

import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class SignUp extends JFrame
{
    private static final long serialVersionUID = 3054293481122038909L;

    private Properties pro = new Properties(); // 最好时静态的,因为账户是共享的

    private JPanel panel = new JPanel();
    private JLabel label = new JLabel("username: ");
    private JTextField field = new JTextField(15);

    private JPanel panel2 = new JPanel();
    private JLabel label2 = new JLabel("password: ");
    private JPasswordField field2 = new JPasswordField(15);

    private JPanel panel3 = new JPanel();
    private JLabel label3 = new JLabel("confirmation: ");
    private JPasswordField field3 = new JPasswordField(15);

    private JPanel panel4 = new JPanel();
    private JButton button = new JButton("OK");
    private JButton button2 = new JButton("Cancel");

    public void initListener()
    {
        field.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                field2.grabFocus();
            }

        });

        field2.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                field3.grabFocus();
            }
        });
        field3.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                ok_actionPerformed(e);
            }

        });

        // OK
        button.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                ok_actionPerformed(e);
            }
        });

        // Cancel
        button2.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                cancel_actionPerformed(e);
            }
        });
    }

    public void ok_actionPerformed(ActionEvent e)
    {
        String userName = field.getText();
        String password = new String(field2.getPassword());
        String password2 = new String(field3.getPassword());
        if (userName.equals(""))
        {
            JOptionPane.showMessageDialog(SignUp.this, "username cannot be empty!");
        } else
        {
            if (password.equalsIgnoreCase(""))
            {
                JOptionPane.showMessageDialog(SignUp.this, "password cannot be empty!");
            } else
            {
                if (password2.equalsIgnoreCase(password))
                {
                    if (isExist(userName))
                    {
                        JOptionPane.showMessageDialog(SignUp.this, "username has been existed!");
                        field.setText("");
                        field2.setText("");
                        field3.setText("");
                    } else
                    {
                        pro.setProperty(userName, password);
                        JOptionPane.showMessageDialog(SignUp.this, "SignUp success!");
                        writeToPro(userName, password); // 将其写入到账户文件中
                        SignUp.this.dispose();
                    }
                } else
                {
                    JOptionPane.showMessageDialog(SignUp.this, "password is not consistent!");
                    field2.setText("");
                    field3.setText("");
                }
            }
        }
    }

    public void cancel_actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }

    public SignUp()
    {
        super("Sign up");

        // 加载账户文件
        try
        {
            pro.load(new FileInputStream(new File("src/res/accouts.properties")));
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        // 初始化窗口组件的监听
        initListener();

        this.setLocation(new Point(300, 230));
        this.setSize(280, 210);

        this.setLayout(new GridLayout(4, 1, 0, 20)); // 垂直间隙为20px
        panel.add(label);
        panel.add(field);
        panel2.add(label2);
        panel2.add(field2);
        panel3.add(label3);
        panel3.add(field3);
        panel4.add(button);
        panel4.add(button2);
        this.add(panel);
        this.add(panel2);
        this.add(panel3);
        this.add(panel4);

        this.setAlwaysOnTop(true);
        this.setResizable(false);
        this.setVisible(true);
    }

    // 如果注册始终可用,就要保存起来,否则不需要写入文件中,注册账户本次使用
    // 将账户名与其对应密码保存到指定的账户文件中
    public void writeToPro(String userName, String password)
    {
        pro.setProperty(userName, password);
        try
        {
            pro.store(new FileOutputStream(new File("src/res/accouts.properties")), "allAccouts");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    // 判断此用户名是否已经存在
    public boolean isExist(String userName)
    {
        Enumeration enumer = pro.propertyNames();
        while (enumer.hasMoreElements())
        {
            String temp = (String) enumer.nextElement();
            if (temp.equals(userName))
            {
                return true;
            }
        }
        return false;
    }
}

產生驗證碼類別##

package ccnu.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Random;

// 用于生成验证码
public class Verification
{
    private static Answer answer = new Answer();
    private static BufferedImage bufferedImage = null;
    private static String result = null;
    private static String words = null;
    private static String words2 = null;

    // 生成验证码
    public static Answer verification()
    {

        bufferedImage = new BufferedImage(200, 35, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        Random rand = new Random();
        for (int i = 0; i < 20; i++)
        {
            Point p1 = new Point(rand.nextInt(200), rand.nextInt(30));
            Point p2 = new Point(rand.nextInt(200), rand.nextInt(30));
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
        }
        g.setColor(Color.RED);
        g.setFont(new Font("楷体", Font.BOLD, 22));
        int plan = 2;
        switch (rand.nextInt(plan))
        {
        case 0:
            plan(g);
            break;
        case 1:
            plan1(g);
            break;
        default:
            break;
        }
        answer.setBufferedImage(bufferedImage);
        answer.setResult(result);
        g.dispose();
        return answer;
    }

    // 方案一
    private static void plan(Graphics g)
    {
        words = ReadTxt.read("/res/words.txt"); // 指定生成验证码问题的资源文件的路径
        Random rand = new Random();
        String first = String.valueOf(words.charAt(rand.nextInt(words.length())));
        String second = String.valueOf(words.charAt(rand.nextInt(words.length())));
        String third = String.valueOf(words.charAt(rand.nextInt(words.length())));
        g.drawString(first, rand.nextInt(40) + 20, rand.nextInt(12) + 15);
        g.drawString(second, rand.nextInt(40) + 80, rand.nextInt(12) + 15);
        g.drawString(third, rand.nextInt(40) + 140, rand.nextInt(12) + 15);
        result = first + second + third;
    }

    // 方案二
    private static void plan1(Graphics g)
    {
        words2 = ReadTxt.read("/res/words2.txt"); // 指定生成验证码问题的资源文件的路径
        Random rand = new Random();
        String first = String.valueOf(words2.charAt(rand.nextInt(words2.length() - 2)));
        String second = String.valueOf(words2.charAt(rand.nextInt(2) + 9));
        String third = String.valueOf(words2.charAt(rand.nextInt(words2.length() - 2)));
        g.drawString(first, rand.nextInt(30) + 20, rand.nextInt(12) + 15);
        g.drawString(second, rand.nextInt(40) + 60, rand.nextInt(12) + 15);
        g.drawString(third, rand.nextInt(30) + 110, rand.nextInt(12) + 15);
        g.drawString("=", rand.nextInt(40) + 150, rand.nextInt(12) + 15);
        if(second.equals("+"))
        {
            result = String.valueOf(Integer.valueOf(first) + Integer.valueOf(third)); 
        }else{
            result = String.valueOf(Integer.valueOf(first) - Integer.valueOf(third)); 
        }
    }

}

讀取產生驗證碼所需檔案類別

package ccnu.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 专门用于读取文件
public class ReadTxt
{
    public static String read(String path) // 根据指定路径path来读取它,并返回它所包含的内容
    {
        StringBuffer sb = new StringBuffer();
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(Verification.class.getResourceAsStream(path)));
            String temp = null;
            while(null != (temp = br.readLine()))
            {
                sb.append(temp);
            }
            br.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }

}

得到產生的驗證碼所包含的資訊類別(圖案、問題)

package ccnu.util;

import java.awt.image.BufferedImage;

// 用于将生成的验证码的图案信息以及问题结果封装
public class Answer
{
    private BufferedImage bufferedImage = null; // 验证码图像
    private String result = null; // 验证码图像问题的答案

    public BufferedImage getBufferedImage()
    {
        return bufferedImage;
    }
    public void setBufferedImage(BufferedImage bufferedImage)
    {
        this.bufferedImage = bufferedImage;
    }
    public String getResult()
    {
        return result;
    }
    public void setResult(String result)
    {
        this.result = result;
    }

}

驗證碼產生漢字辨識的問題的檔案words.txt

如: 中國湖北省武漢市漢東大學政法學院

驗證碼產生算術運算的問題的檔案words2.txt

123456789 -

提示圖片

java如何實作登入視窗

java如何實作登入視窗

#登入效果

java如何實作登入視窗

###

以上是java如何實作登入視窗的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

如何將Java的RMI(遠程方法調用)用於分佈式計算?如何將Java的RMI(遠程方法調用)用於分佈式計算?Mar 11, 2025 pm 05:53 PM

本文解釋了用於構建分佈式應用程序的Java的遠程方法調用(RMI)。 它詳細介紹了接口定義,實現,註冊表設置和客戶端調用,以解決網絡問題和安全性等挑戰。

如何使用Java的插座API進行網絡通信?如何使用Java的插座API進行網絡通信?Mar 11, 2025 pm 05:53 PM

本文詳細介紹了用於網絡通信的Java的套接字API,涵蓋了客戶服務器設置,數據處理和關鍵考慮因素,例如資源管理,錯誤處理和安全性。 它還探索了性能優化技術,我

如何在Java中創建自定義網絡協議?如何在Java中創建自定義網絡協議?Mar 11, 2025 pm 05:52 PM

本文詳細介紹了創建自定義Java網絡協議。 它涵蓋協議定義(數據結構,框架,錯誤處理,版本控制),實現(使用插座),數據序列化和最佳實踐(效率,安全性,維護

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境