1

我正在创建一个“商店”程序,基本上可以让员工使用我提供的用户名和密码登录。登录后,员工可以看到一个带有四个按钮的“主菜单”:销售登记、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;
        }
    }
}                                                                               
4

1 回答 1

2
  1. 停止使用null布局,说真的,这是更多问题的根源,然后是 Swing 的任何其他问题
  2. 使用 向面板添加组件时CardLayout,每个面板必须有一个名称
  3. 在您的actionPerformed方法中,这不是CardLayout工作方式。首先,您正在创建一个 的新实例CardLayout,其中不包含任何组件,那么您如何期望它能够突然弄清楚要切换到什么?使用CardLayout#show时,组件引用是开始管理的父组件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);
        }
    }
}
于 2013-07-05T00:23:08.433 回答