java - 将读/写类合并到基本 GUI 登录中

标签 java swing

我是一个十足的菜鸟,学习 Java 才几周时间。作为我负责编写的一段代码的一部分,我必须创建一个登录页面,该页面接收用户名和密码,然后对照保存该信息的 txt 文件进行检查。一旦验证,用户就会继续我需要创建的基于 GUI 的游戏。

我有以下代码片段,我知道它们都是单独工作的,我正在努力做的是将它们全部组合在一起作为一个整体工作。

登录代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class Login 
{
private static JFrame frame;
private static JPanel northPanel;
private static JPanel centerPanel;
private static JPanel southPanel;
private static JLabel headingLabel;
private static JLabel usernameLabel;
private static JLabel passwordLabel;
private static JTextField usernameField;
private static JPasswordField passwordField;
private static JButton loginBtn;

public void start() 
{
    try 
    {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } 
    catch (Exception e) 
    {

    }

    new Login().buildLogin();
}

private void buildLogin() 
{
    // Build Objects
    frame = new JFrame();
    northPanel = new JPanel();
    centerPanel = new JPanel();
    southPanel = new JPanel();
    headingLabel = new JLabel();
    usernameLabel = new JLabel();
    passwordLabel = new JLabel();
    usernameField = new JTextField();
    passwordField = new JPasswordField();
    loginBtn = new JButton();

    // Labels
    headingLabel.setText("Login");
    headingLabel.setForeground(Color.white);
    headingLabel.setVisible(true);

    usernameLabel.setText("   Username: ");
    usernameLabel.setForeground(Color.blue);
    usernameLabel.setVisible(true);

    passwordLabel.setText("   Password: ");
    passwordLabel.setForeground(Color.blue);
    passwordLabel.setVisible(true);

    // Buttons
    loginBtn.setText("Login");
    loginBtn.setVisible(true);
    loginBtn.addActionListener(new Validate1());

    // Panels
    northPanel.add(headingLabel);
    northPanel.setBackground(Color.blue);
    centerPanel.add(usernameLabel);
    centerPanel.add(usernameField);
    centerPanel.add(passwordLabel);
    centerPanel.add(passwordField);
    centerPanel.setLayout(new GridLayout(2, 2));
    southPanel.add(loginBtn);

    // JFrame
    frame.getContentPane().add(BorderLayout.NORTH, northPanel);
    frame.getContentPane().add(BorderLayout.CENTER, centerPanel);
    frame.getContentPane().add(BorderLayout.SOUTH, southPanel);
    frame.setSize(300, 150);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
}

// Validate1 Class
static class Validate1 implements ActionListener 
{
    @SuppressWarnings("deprecation")
    public void actionPerformed(ActionEvent e) 
    {
        String username = null;
        String password = null;

        try 
        {
            username = usernameField.getText().toUpperCase().trim();
            password = passwordField.getText().toUpperCase().trim();

            if (username.equals("") && password.equals("")) 
            {
                usernameLabel.setForeground(Color.red);
                passwordLabel.setForeground(Color.red);
            } 
            else 
            {
                if (username.equals("")) 
                {
                    usernameLabel.setForeground(Color.red);
                    passwordLabel.setForeground(Color.blue);
                } 
                else 
                {
                    if (password.equals("")) 
                    {
                        usernameLabel.setForeground(Color.blue);
                        passwordLabel.setForeground(Color.red);
                    } 
                    else 
                    {
                        usernameLabel.setForeground(Color.red);
                        passwordLabel.setForeground(Color.red);
                        new Login().validate2(username, password);
                    }
                }
            }
        } 
        catch (Exception validateError) 
        {
            JOptionPane.showMessageDialog(null, "There was an error Class::Login Class Validate1", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

//Validate2 Method
private void validate2(String getUsername, String getPassword)
{
    String username = null;
    String password = null;

    try
    {
        username = getUsername.toUpperCase();
        password = getPassword.toUpperCase();

        if (username.contains(" ") && password.contains(" ")) 
        {
            JOptionPane.showMessageDialog(null, "The username and password is invalid", "Error", JOptionPane.ERROR_MESSAGE);
        } 
        else 
        {
            if (username.contains(" ")) 
            {
                JOptionPane.showMessageDialog(null, "The username is invalid", "Error", JOptionPane.ERROR_MESSAGE);
            } 
            else 
            {
                if (password.contains(" ")) 
                {
                    JOptionPane.showMessageDialog(null, "The password is invalid", "Error", JOptionPane.ERROR_MESSAGE);
                } 
                else 
                {
                    usernameLabel.setForeground(Color.red);
                    passwordLabel.setForeground(Color.red);
                    System.out.println("All good!!");
                }
            }
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, "Error in Class::Login Method:valsidate2","Error", JOptionPane.ERROR_MESSAGE);

    }
}
}

登录主要代码:

public class Main 
{

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

}

}

文件数据:

import java.io.*;

public class FileData 
{

public static void main(String[] args) throws IOException
{
    String file_name = "PATH TO THE TEXT FILE WOULD BE HERE";

    try
    {
        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();

        for(int i = 0; i < aryLines.length; i++)
        {
            System.out.println(aryLines[i]);
        }
    }
    catch (IOException e)
    {
        //System.out.println(e.getMessage());
        System.out.println("Sorry, dude - no can do!!!\n" + e.getMessage());
    }

    try
    {
        WriteFile data = new WriteFile(file_name , true );
        data.writeToFile("This is another line of text");
    }
    catch(IOException e)
    {
        System.out.println("Sorry, dude - no can do!!!\n" + e.getMessage());
    }

    System.out.println("Text File Written To");
}

}

读取文件:

import java.io.*;

public class ReadFile 
{
private String path;

public ReadFile(String file_path)
{
    path = file_path;
}

public String[] OpenFile() throws IOException
{
    FileReader inFile = new FileReader(path);
    BufferedReader textReader = new BufferedReader(inFile);

    int numOfLines = readLines();
    String[] textData = new String[numOfLines];

    for(int i = 0; i < numOfLines; i++)
    {
        textData[i] = textReader.readLine();
    }

    textReader.close();
    return textData;
}

int readLines() throws IOException
{
    FileReader file_to_read = new FileReader(path);
    BufferedReader bf = new BufferedReader(file_to_read);

    String aLine;
    int numOfLines = 0;

    while((aLine = bf.readLine()) != null)
    {
        numOfLines++;
    }

    bf.close();

    return numOfLines;
}
}  

写入文件:

import java.io.*;

public class WriteFile 
{
private String path;
private boolean append_to_file = false;

public WriteFile(String file_path)
{
    path = file_path;
}

public WriteFile(String file_path, boolean append_value)
{
    path = file_path;
    append_to_file = append_value;
}

public void writeToFile(String textLine) throws IOException
{
    FileWriter write = new FileWriter(path, append_to_file);
    PrintWriter print_line = new PrintWriter(write);

    print_line.printf("%s" + "%n" , textLine);

    print_line.close();
}
}

最佳答案

请参阅代码中的注释。我希望能帮助您向前迈出一步:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
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 javax.swing.UIManager;

public class Login {

    //use JDialog to control modality and
    //easier to get a return value
    //private static JFrame frame;
    private static JDialog frame;
    private static JPanel northPanel;
    private static JPanel centerPanel;
    private static JPanel southPanel;
    private static JLabel headingLabel;
    private static JLabel usernameLabel;
    private static JLabel passwordLabel;
    private static JTextField usernameField;
    private static JPasswordField passwordField;
    private static JButton loginBtn;

    //Add a login fail / success flag
    boolean loginSuccess = false;

    public static void main(String[] args)
    {
        //have the login process return a fail / success boolean
        boolean loginSuccess = new Login().start();

        System.out.println(loginSuccess);

        //if login is successful run game 
        //else quit / show error / retry 
    }

    //change return type to boolean (fail / success flag)
    public boolean start()
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) {e.printStackTrace();   }

        //no need to initialize Login again
        //new Login().buildLogin();
        //use
         buildLogin();

         return loginSuccess;
    }

    private void buildLogin()
    {

        // Build Objects
        frame = new JDialog();  //instead of frame = new JFrame();

        northPanel = new JPanel();
        centerPanel = new JPanel();
        southPanel = new JPanel();
        headingLabel = new JLabel();
        usernameLabel = new JLabel();
        passwordLabel = new JLabel();
        usernameField = new JTextField();
        passwordField = new JPasswordField();
        loginBtn = new JButton();

        // Labels
        headingLabel.setText("Login");
        headingLabel.setForeground(Color.white);
        headingLabel.setVisible(true);

        usernameLabel.setText("   Username: ");
        usernameLabel.setForeground(Color.blue);
        usernameLabel.setVisible(true);

        passwordLabel.setText("   Password: ");
        passwordLabel.setForeground(Color.blue);
        passwordLabel.setVisible(true);

        // Buttons
        loginBtn.setText("Login");
        loginBtn.setVisible(true);

        //instead of
        //loginBtn.addActionListener(new Validate1());
        //add an action listener and have it run validate1()
        loginBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                validate1();

            }
        });
        // Panels
        northPanel.add(headingLabel);
        northPanel.setBackground(Color.blue);
        centerPanel.add(usernameLabel);
        centerPanel.add(usernameField);
        centerPanel.add(passwordLabel);
        centerPanel.add(passwordField);
        centerPanel.setLayout(new GridLayout(2, 2));
        southPanel.add(loginBtn);

        // JDialog
        frame.getContentPane().add(BorderLayout.NORTH, northPanel);
        frame.getContentPane().add(BorderLayout.CENTER, centerPanel);
        frame.getContentPane().add(BorderLayout.SOUTH, southPanel);
        frame.setSize(300, 150);
        frame.setResizable(false);

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE /* not valid for a JDialog JFrame.EXIT_ON_CLOSE*/);
        //add modality to wait for the frame to close
        frame.setModalityType(ModalityType.APPLICATION_MODAL);
        frame.setLocationRelativeTo(null);

        //set frame to visible after it has been completely set
        //including its modality
        frame.setVisible(true);
    }

    // Validate1 Class
    //can be implemented a simple methos
    //static class Validate1 implements ActionListener
    private void validate1()
    {

        String username = null;
            String password = null;

            try
            {
                username = usernameField.getText().toUpperCase().trim();
                password = passwordField.getText().toUpperCase().trim();

                if (username.equals("") && password.equals(""))
                {
                    usernameLabel.setForeground(Color.red);
                    passwordLabel.setForeground(Color.red);
                }
                else
                {
                    if (username.equals(""))
                    {
                        usernameLabel.setForeground(Color.red);
                        passwordLabel.setForeground(Color.blue);
                    }
                    else
                    {
                        if (password.equals(""))
                        {
                            usernameLabel.setForeground(Color.blue);
                            passwordLabel.setForeground(Color.red);
                        }
                        else
                        {
                            usernameLabel.setForeground(Color.red);
                            passwordLabel.setForeground(Color.red);

                            //no need to initialize Login again
                            //new Login().validate2(username, password);
                            validate2(username, password);
                        }
                    }
                }
            }
            catch (Exception validateError)
            {
                JOptionPane.showMessageDialog(null, "There was an error Class::Login Class Validate1", "Error", JOptionPane.ERROR_MESSAGE);
            }
    }

    //Validate2 Method
    private void validate2(String getUsername, String getPassword)
    {
        String username = null;
        String password = null;

        try
        {
            username = getUsername.toUpperCase();
            password = getPassword.toUpperCase();

            //the validation logic needs to be revised 
            if (username.contains(" ") && password.contains(" "))
            {
                JOptionPane.showMessageDialog(null, "The username and password is invalid", "Error", JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                if (username.contains(" "))
                {
                    JOptionPane.showMessageDialog(null, "The username is invalid", "Error", JOptionPane.ERROR_MESSAGE);
                }
                else
                {
                    if (password.contains(" "))
                    {
                        JOptionPane.showMessageDialog(null, "The password is invalid", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                    else
                    {
                        usernameLabel.setForeground(Color.red);
                        passwordLabel.setForeground(Color.red);
                        System.out.println("All good!!");

                        ///////////////////////////////////////////////
                        //set return value to indicate successful login
                        loginSuccess = true;
                    }
                }
            }
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "Error in Class::Login Method:valsidate2","Error", JOptionPane.ERROR_MESSAGE);

        }
    }
}

如有需要澄清的地方,请随时询问。

关于java - 将读/写类合并到基本 GUI 登录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38804795/

相关文章:

java - 由于存在粘性按钮而无法单击按钮

java - 这会导致垃圾收集问题吗

java - 如何在用户浏览 TreeView 时操作一组面板?

java - IllegalArgumentException 向容器添加窗口。

java - Swing 线程安全

java - Spring JavaConfig 和 Tomcat 8

java - 无法启动 Appium session ,错误为 : Error: Bad app:

java - 设置 LayoutParams 时出现 NullPointerException

java - 接受用户的大量输入

java - JPanel 中的 JLabel 对齐