如何将 CardLayout 用于我的 Java 程序的登录和菜单项 [英] How do I use CardLayout for my Java Program for Login and Menu Items

查看:21
本文介绍了如何将 CardLayout 用于我的 Java 程序的登录和菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个商店"程序,基本上可以让员工使用我提供的用户名和密码登录.登录后,员工可以看到一个带有四个按钮的主菜单":销售登记、PLU 设置、设置和注销.在此屏幕中,员工可以通过单击任何按钮导航到该屏幕来继续.我不希望每次单击按钮时都会弹出一个新窗口,而是希望有一些过渡(或没有过渡)以转到单击的页面.

I am creating a "Store" program that basically can allow an employee to log in with a username and password I provide. After logging in, the employee can then see a "main menu" with four buttons: Sales Register, PLU Settings, Settings, and Logout. From this screen, the employee can proceed by clicking on any of the buttons to navigate to that screen. I do not want a new window to popup every time a button is clicked, but instead I want there to be some transition (or no transition) to go to the page that is clicked.

举个例子:当员工启动程序时,他/她会看到登录菜单.然后员工输入他/她的登录信息并点击登录.如果信息不正确,则会提示员工重新输入信息.如果信息正确,员工现在被发送到主菜单.在主菜单,员工选择销售登记",程序进入销售登记.所有这些都应该发生在一个窗口中.

So to give an example: When the employee starts the program, he/she is greeted with the login menu. Then the employee enters his/her login information and hits login. If the info is incorrect, the employee is prompted to re-enter the info. If the info is correct, the employee is now sent to the main menu. At the main menu the employee selects "Sales Register" and the program goes to the sales register. All of this should happen in one window.

到目前为止,我已经添加了我能够做的代码.我已经创建了所有按钮和标签,但我无法让它们显示在 JFrame 上并使用 CardLayout.另外,我不知道如何将登录代码与 CardLayout 链接.

I have added the code of what I have been able to do, so far. I have created all of the buttons and labels, but I can't get them to show up on the JFrame and use the CardLayout. Also, I do not know how to link the Login code with the CardLayout.

谢谢你帮助我.代码如下:

Thank you for helping me. Here is the code:

主菜单代码 (storeMainMenu.java)

Main Menu Code (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):

Login Code (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)

Database Code (the login code references this code for the MySQL info) (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. 别再使用 null 布局了,说真的,这是比 Swing 更多问题的根源
  2. 使用 CardLayout 向面板添加组件时,每个面板都必须有一个名称
  3. 在您的 actionPerformed 方法中,这不是 CardLayout 的工作方式.首先,您正在创建一个新的 CardLayout 实例,其中不包含任何组件,那么您如何期望它能够突然弄清楚要切换到什么?使用 CardLayout#show 时,组件引用是由 CardLayout
  4. 开始管理的父组件
  1. Stop using null layouts, seriously, this is the source of more problems then just about anything else with Swing
  2. When adding components to a panel using CardLayout, each panel MUST have a name
  3. In your actionPerformed method, this is not how CardLayout works. To start with, you're creating a new instance of CardLayout, which contains NO components, so how did you expect it to be able to suddenly figure out what to switch to? When using CardLayout#show, the component reference is the parent component that that is begin manged by the CardLayout

更新示例

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MyCardLayout {

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

    public MyCardLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel mainPane;
        private JPanel navPane;
        private List<String> pages;
        private int currentPage;

        public TestPane() {
            pages = new ArrayList<>(25);
            setLayout(new BorderLayout());

            mainPane = new JPanel(new CardLayout());
            navPane = new JPanel();

            for (int index = 0; index < 10; index++) {
                addPageTo(mainPane, "Page" + index, new JLabel("Page " + index, JLabel.CENTER));
            }

            JButton btnPrev = new JButton("<<");
            JButton btnNext = new JButton(">>");

            navPane.add(btnPrev);
            navPane.add(btnNext);

            btnPrev.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setCurrentPage(getCurrentPage() - 1);
                }
            });
            btnNext.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setCurrentPage(getCurrentPage() + 1);
                }
            });

            add(mainPane);
            add(navPane, BorderLayout.SOUTH);

            setCurrentPage(0);
        }

        public int getCurrentPage() {
            return currentPage;
        }

        protected void setCurrentPage(int page) {
            if (pages.size() > 0) {
                if (page < 0) {
                    page = pages.size() - 1;
                } else if (page >= pages.size()) {
                    page = 0;
                }

                currentPage = page;
                CardLayout layout = (CardLayout)mainPane.getLayout();
                layout.show(mainPane, pages.get(currentPage));
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void addPageTo(JPanel pane, String name, Component comp) {
            pages.add(name);
            pane.add(comp, name);
        }
    }
}

这篇关于如何将 CardLayout 用于我的 Java 程序的登录和菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆