Как я могу использовать CardLayout для моей Java-программы для входа в систему и пунктов меню

Я создаюХранить" Программа, которая в основном может позволить сотруднику войти в систему с помощью имени пользователя и пароля, которые я предоставляю. После входа сотрудник может увидеть "главное меню" с четырьмя кнопками: регистр продаж, настройки PLU, настройки и выход из системы. На этом экране сотрудник может перейти, нажав любую из кнопок, чтобы перейти к этому экрану. Я не хочу, чтобы новое окно появлялось при каждом нажатии кнопки, но вместо этого я хочу, чтобы был переход (или отсутствие перехода), чтобы перейти на страницу, на которую нажимали.

Итак, приведем пример: когда сотрудник запускает программу, его приветствует меню входа в систему. Затем сотрудник вводит свою регистрационную информацию и нажимает на нее. Если информация неверна, сотруднику предлагается повторно ввести информацию. Если информация верна, сотрудник отправляется в главное меню. В главном меню сотрудник выбираетРеестр продаж » и программа переходит в реестр продаж. Все это должно происходить в одном окне.

Я добавил код того, что мне удалось сделать до сих пор. Я создал все кнопки и метки, но могучтобы они появлялись в JFrame и использовали CardLayout. Кроме того, я не знаю, как связать код входа с CardLayout.

Спасибо за помощь мне. Вот код:

Код главного меню (storeMainMenu.java)

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

public class storeMainMenu implements ActionListener {

    String loginString = "Login";
    String salesRegisterString = "Sales Register";
    String pluSettingsString = "PLU Settings";
    String settingsString = "Settings";
    String logoutString = "Logout";

    //JFrame
    int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    int height = Toolkit.getDefaultToolkit().getScreenSize().height;
    Color myColor = Color.decode("#F1E0B8");

    //JPanel
    static JPanel buttonPanel = new JPanel();
    JPanel test1 = new JPanel();
    JPanel test2 = new JPanel();
    JPanel test3 = new JPanel();
    JPanel test4 = new JPanel();

    //Buttons
    JButton salesRegister = new JButton("Sales Register");
    JButton pluSettings = new JButton("PLU Settings");
    JButton settings = new JButton("Settings");
    JButton logout = new JButton("Logout");

    //Label
    JLabel header = new JLabel("Store Register");
    JLabel test_1 = new JLabel("Test 1");
    JLabel test_2 = new JLabel("Test 2");
    JLabel test_3 = new JLabel("Test 3");
    JLabel test_4 = new JLabel("Test 4");

    public storeMainMenu ()
    {
        //Header 
        header.setFont(new Font("Myriad", Font.PLAIN, 50));
        header.setBounds((width/6),0,1000,100);

        //Sales Register Bounds
        salesRegister.setBounds(100, 100, 500, 250);

        //PluSettings Bounds
        pluSettings.setBounds(700, 100, 500, 250);

        //Settings Bounds
        settings.setBounds(100, 500, 500, 250);

        //Logout Bounds
        logout.setBounds(700, 500, 500, 250);

        //JPanel bounds
        buttonPanel.setLayout(null);

        //TEST JPANEL
        test1.setLayout(null);
        test2.setLayout(null);
        test3.setLayout(null);
        test4.setLayout(null);

        test1.setSize(width, height);
        test2.setSize(width,height);
        test3.setSize(width, height);
        test4.setSize(width, height);

        //Test JPANEL Labels
        test_1.setFont(new Font("Myriad", Font.PLAIN, 50));
        test_1.setBounds((width/6),0,1000,100);
        test_2.setFont(new Font("Myriad", Font.PLAIN, 50));
        test_2.setBounds((width/6),0,1000,100);
        test_3.setFont(new Font("Myriad", Font.PLAIN, 50));
        test_3.setBounds((width/6),0,1000,100);
        test_4.setFont(new Font("Myriad", Font.PLAIN, 50));
        test_4.setBounds((width/6),0,1000,100);

        //Adding to test JPanel
        test1.add(test_1);
        test2.add(test_2);
        test3.add(test_3);
        test4.add(test_4);

        //Adding to JFrame
        buttonPanel.add(header);
        buttonPanel.add(salesRegister);
        buttonPanel.add(pluSettings);
        buttonPanel.add(settings);
        buttonPanel.add(logout);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        CardLayout cardLayout = new CardLayout();

        if (e.getSource() == salesRegister) {
            cardLayout.show(test1, salesRegisterString);
        }
        if (e.getSource() == pluSettings) {
            cardLayout.show(test2, pluSettingsString);
        }
        if (e.getSource() == settings) {
            cardLayout.show(test3, settingsString);
        }
        if (e.getSource() == logout) {
            cardLayout.show(test4, logoutString);
        }
    }


    static void createAndShowGUI() {
            int width = Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = Toolkit.getDefaultToolkit().getScreenSize().height;
            Color myColor = Color.decode("#F1E0B8");

            JFrame frame = new JFrame("Store");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
            frame.setSize(width, height);
            frame.setBackground(myColor);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            frame.add(buttonPanel);
        }


    public static void main (String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }


}

Код для входа (login.java):

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

@SuppressWarnings("serial")
public class login extends JFrame {

    //declaring our swing components
    JLabel l_name,l_pass;
    JTextField t_name;
    JPasswordField t_pass;     //A special JTextField but hides input text
    JButton button;
    Container c;
    boolean checkLogin = false;

    //a inner class to handling ActionEvents
    handler handle;

    //a separate class for processing database connection and authentication
    database db;    

    login()
    {
        super("Login form");

        c=getContentPane();
        c.setLayout(new FlowLayout());

        //extra classes
        db=new database();
            handle =new handler();

                //swing components
        l_name=new JLabel("Username");
        l_pass=new JLabel("Password");
        t_name=new JTextField(10);
        t_pass=new JPasswordField(10);
        button=new JButton("Login");

        //adding actionlistener to the button
        button.addActionListener(handle);

        //add to contaienr
        c.add(l_name);
        c.add(t_name);
        c.add(l_pass);
        c.add(t_pass);
        c.add(button);
        //visual
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200,175);

    }
    public static void main(String args[])
    {
        @SuppressWarnings("unused")
        login sample=new login();
    }
    //an inner class .You can also write as a separate class
    class handler implements ActionListener
    {
        //must implement method
        //This is triggered whenever the user clicks the login button
        public void actionPerformed(ActionEvent ae)
        {
            //checks if the button clicked
            if(ae.getSource()==button)
            {
                char[] temp_pwd=t_pass.getPassword();
                String pwd=null;
                pwd=String.copyValueOf(temp_pwd);
                System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);

                //The entered username and password are sent via "checkLogin()" which return boolean
                if(db.checkLogin(t_name.getText(), pwd))
                {
                    //a pop-up box
                    JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
                                        JOptionPane.INFORMATION_MESSAGE);
                    checkLogin = true;
                }
                else
                {
                    //a pop-up box
                    JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
                                        JOptionPane.ERROR_MESSAGE);
                    checkLogin = false;
                }
            }//if
        }//method

    }//inner class

}

Код базы данных (код логина ссылается на этот код для информации MySQL) (database.java)

import java.sql.*;
public class database 
{
    Connection con;
    PreparedStatement pst;
    ResultSet rs;
    database()
    {
        try{

            //MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
            //ALSO SET THE CLASSPATH
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/SchoolStoreUsers","root","schoolstore");
                        pst=con.prepareStatement("select * from users where uname=? and pwd=?");

           }
        catch (Exception e) 
        {
            System.out.println(e);
        }
    }
        //ip:username,password
        //return boolean
    public Boolean checkLogin(String uname,String pwd)
    {
        try {

            pst.setString(1, uname); //this replaces the 1st  "?" in the query for username
            pst.setString(2, pwd);    //this replaces the 2st  "?" in the query for password
            //executes the prepared statement
            rs=pst.executeQuery();
            if(rs.next())
            {
                //TRUE iff the query founds any corresponding data
                return true;
            }
            else
            {
                return false;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("error while validating"+e);
            return false;
        }
    }
}                                                                               

Ответы на вопрос(1)

Ваш ответ на вопрос