如何有效利用cardlayout在java中,以各种面板的构造函数内使用面板按键切换 [英] How to effectively use cardlayout in java in order to switch from panel using buttons inside various panel constructors

查看:202
本文介绍了如何有效利用cardlayout在java中,以各种面板的构造函数内使用面板按键切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来使用cardlayout和我对如何实现它的一些问题。我首先想知道实施cardlayout,这样我可以从面板切换到面板的最佳途径。我的主要问题是如何使用我的面板的构造函数里面按钮从面板切换到面板。我刚开始今天在这个项目上工作,所以你会看到一些code,它没有完成或没有意义。我第一次尝试,使我所有的类来扩展JFrame的,但导致多个不必要的窗口。如果我能得到关于如何有效地使用cardlayout以及如何我的其他面板的构造函数中切换使用按钮面板一些例子。我使用cardlayout尝试只工作了,我在我的GUI类创建但是这不是我想要的结果按钮。如果可以的话,并在此先感谢,请帮助。

这是我的主类。

 公共类控制器{
    公共静态无效的主要(字串[] args){        新的GUI();
    }
}

这是我的GUI类。

 进口java.awt.CardLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;进口javax.swing.Box中;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.JPasswordField中;
进口javax.swing.JTextField中;公共类桂扩展的JFrame {
    主页首页=新的主页();
    公众的JPanel loginPanel =新textEmailLog()
    registerPanel =新注册()
    homePanel =新的主页()的viewPanel =新emailView()
    loadPanel =新loadEmail()的ContentPanel =新JPanel(新CardLayout());
    CardLayout cardLayout =新CardLayout();
    公共桂(){
        超(电子邮件数据库计划);
        的setSize(700700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        contentPanel.setLayout(cardLayout);        contentPanel.add(loginPanel,登录);
        contentPanel.add(registerPanel,注册);
        contentPanel.add(homePanel,家);
        contentPanel.add(viewPanel中,查看);
        contentPanel.add(loadPanel,装载);
        this.setContentPane(的ContentPanel);        cardLayout.show(的ContentPanel,登录);
        调用setVisible(真);
    }

我的登录面板类

 进口java.awt.CardLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;进口javax.swing.Box中;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.JPasswordField中;
进口javax.swing.JTextField中;//面板已被添加
公共类textEmailLog继承JPanel {
        JPanel的logGui = NULL;
        JButton的registerBut,logBu​​t;
        JTextField的登录;    公共textEmailLog(){
        //默认特征
        的setSize(700700);
        的setName(邮件数据库);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //标签的用户名和密码
        JLabel的userLab =新的JLabel(用户名);
        JLabel的pwLab =新的JLabel(密码);        //文本框的用户名和密码
        登录=新的JTextField(,15);
        JPasswordField中密码=新JPasswordField(,15);
        Password.setEchoChar('*');        //登录按钮,确认用户名和密码
        logBu​​t =的新的JButton(登录);
        logBu​​t.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                //在登录前需要检查的正则表达式中                如果(e.getSource()== logBu​​t){
                    / *面板更改为主页
                    如果(Login.getText()的equals()及&安培; Password.getText()equals()方法。){                    }
                * /
                    新的主页();
                }
            }
        });        registerBut =的新的JButton(注册);
        registerBut.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()== registerBut){
                    //面板改为寄存器面板
                }
            }        });        //框布局JComponent上的组织
        框verticalContainer = Box.createVerticalBox();
        框horizo​​ntalContainer = Box.createHorizo​​ntalBox();
        框mergerContainer = Box.createVerticalBox();
        //添加到面板
        verticalContainer.add(Box.createVerticalStrut(300)); //相对开始到中心
        verticalContainer.add(userLab); //登录标签和文本
        verticalContainer.add(登录);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(pwLab); //密码标签和文本
        verticalContainer.add(密码);
        verticalContainer.add(Box.createVerticalStrut(5));
        horizo​​ntalContainer.add(registerBut); //注册按钮
        horizo​​ntalContainer.add(Box.createHorizo​​ntalStrut(5));
        horizo​​ntalContainer.add(logBu​​t); //登录按钮        //结合了垂直和水平容器
        mergerContainer.add(verticalContainer);
        mergerContainer.add(horizo​​ntalContainer);
        加(mergerContainer);
        //this.add(logGui);
        调用setVisible(真);    }

}

我的注册类面板

 进口java.awt.Color中;
    进口java.awt.event.ActionEvent中;
    进口java.awt.event.ActionListener;    进口javax.swing.Box中;
    进口javax.swing.JButton中;
    进口javax.swing.JFrame中;
    进口javax.swing.JLabel中;
    进口javax.swing.JPanel中;
    进口javax.swing.JPasswordField中;
    进口javax.swing.JTextField中;    //否面板除了
    公共类注册继承JPanel {
            JButton的提交,previous;
            JLabel的firstLab,lastLab,userLab,passwordLab,repassLab,地址,emailAdd,errorLabel;
            JTextField的firstText,lastText,userText,addText,emailAddText;
            JPasswordField中passwordText,repassText;        公共寄存器(){
            的setSize(700700);
            //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //寄存器值和他们的标签和文本框
            firstLab =新的JLabel(名字:);
            firstText =新的JTextField(,25);
            lastLab =新的JLabel(姓氏:);
            lastText =新的JTextField(,40);
            userLab =新的JLabel(用户名:);
            userText =新的JTextField(,25);
            passwordLab =新的JLabel(密码:);
            passwordText =新JPasswordField(,25);
            passwordText.setEchoChar('*');
            repassLab =新的JLabel(确认密码);
            repassText =新JPasswordField(,25);
            repassText.setEchoChar('*');
            地址=新的JLabel(地址);
            addText =新的JTextField(,50);
            emailAdd =新的JLabel(电子邮件地址:);
            emailAddText =新的JTextField(,50);            //为reigstration发出错误消息
            errorLabel =新的JLabel();
            errorLabel.setForeground(Color.red);            提交=新的JButton(提交);            submit.addActionListener(新的ActionListener(){                @燮pressWarnings(德precation)
                公共无效的actionPerformed(ActionEvent的五){
                    // TODO自动生成方法存根
                    如果(e.getSource()==提交){
                        与正则表达式的方法,如果已创建并需要创建语句//确认
                        如果(firstText.getText()。长度()== 0){
                            errorLabel.setText(*您没有输入一个名字!);
                        }其他
                        如果(lastText.getText()。长度()== 0){
                            errorLabel.setText(*您还没有进入最后的名字!);
                        }其他
                        如果(userText.getText()。长度()== 0){
                            errorLabel.setText(*您没有输入用户名!);
                        }其他
                        如果(passwordText.toString()。长度()== 0){
                            errorLabel.setText(*您还没有输入密码!);
                        }其他
                        如果(repassText.toString()。长度()== 0){
                            errorLabel.setText(*你有没有符合你的密码!);
                        }
                        如果(addText.getText()。长度()== 0){
                            errorLabel.setText(*您还没有输入的地址!);
                        }其他
                        如果(emailAddText.getText()。长度()== 0){
                            errorLabel.setText(*您还没有输入电子邮件地址的!);
                        }其他
                        如果(userText.getText()长()< 8){
                            errorLabel.setText(*用户名是太短了!);
                        }
                        其他
                        如果(!(passwordText.toString()。相匹配(repassText.toString()))){
                            errorLabel.setText(密码不匹配!);
                        }
                        其他
                        如果(!isValidEmailAddress(emailAddText.getText())){
                            errorLabel.setText(*电子邮件地址无效!);
                        }
                        其他
                        如果(!isValidAddress(addText.getText())){
                            errorLabel.setText(*无效地址!);
                        }
                    }
                }            });
            //返回previous页
            previous =的新的JButton(previous页);
            previous.addActionListener(新的ActionListener(){                公共无效的actionPerformed(ActionEvent的五){
                    // TODO自动生成方法存根
                    如果(e.getSource()== previous){
                        //card.show(login面板);
                    }
                }            });
            框verticalContainer = Box.createVerticalBox();
            框horizo​​ntalContainer = Box.createHorizo​​ntalBox();
            框mergerContainer = Box.createVerticalBox();            verticalContainer.add(Box.createVerticalStrut(150));
            verticalContainer.add(firstLab);
            verticalContainer.add(firstText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(lastLab);
            verticalContainer.add(lastText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(userLab);
            verticalContainer.add(userText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(passwordLab);
            verticalContainer.add(passwordText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(repassLab);
            verticalContainer.add(repassText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(地址);
            verticalContainer.add(addText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(emailAdd);
            verticalContainer.add(emailAddText);
            verticalContainer.add(Box.createVerticalStrut(5));            //水平
            verticalContainer.add(Box.createVerticalStrut(5));
            horizo​​ntalContainer.add(提交);
            horizo​​ntalContainer.add(Box.createHorizo​​ntalStrut(5));
            horizo​​ntalContainer.add(previous);            //合并
            mergerContainer.add(verticalContainer);
            mergerContainer.add(horizo​​ntalContainer);            加(mergerContainer);
            调用setVisible(真);
        }        //正则表达式检查有效电子邮件
    公共布尔isValidEmailAddress(字符串email){
            java.util.regex.Pattern中的P = java.util.regex.Pattern.compile([A-ZA-Z0-9 ._ \\\\% - ] + @ [A-ZA-Z0-9 .-] + \\ \\ [A-ZA-Z] {2,4});
            java.util.regex.Matcher中的M = p.matcher(电子邮件);
            返回m.matches();        }
    //正则表达式检查有效地址
    公共布尔isValidAddress(字符串地址){
        java.util.regex.Pattern中的P = java.util.regex.Pattern.compile(\\\\Ð{1,3}?\\\\Ð{0,3} \\\\ S [A-ZA-Z] {2 30} \\\\ S [A-ZA-Z] {2,15});
        java.util.regex.Matcher中的M = p.matcher(地址);
        返回m.matches();    }
    }

首页面板类

 进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JPanel中;//否面板然而,
@燮pressWarnings(串行)
公共类网页继承JPanel {        JButton的uploadEmail,viewEmail;
    公共主页(){
        的setSize(700700);
        uploadEmail =的新的JButton(上传您的电子邮件);
        uploadEmail.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()== uploadEmail){
                    新loadEmail();
                }
            }        });
        viewEmail =的新的JButton(查看邮件);
        viewEmail.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()== viewEmail){
                    新emailView();
                }
            }        });        加(uploadEmail);
        加(viewEmail);
        调用setVisible(真);
    }
}

我查看电子邮件面板

 进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;进口javax.swing.Box中;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.JTable中;
进口javax.swing.JTextArea中;
进口javax.swing.JTextField中;
公共类emailView继承JPanel {
        JPanel的viewPanel中;
        JButton的注销,删除,网页;
        JTable中的emailList;        //不能被编辑,或者可以是在一个新的面板
        / *
        JLabel的fileLab,toLab,fromLab,subjectLab,topicLab,emailLab,notesLab,attachLab;
        JTextField的FILETEXT,toText,fromText,subjectText,topicText;
        JTextArea中emailText,notesText,attachText;
        * /
    公共emailView(){
        的setSize(700700);
        调用setVisible(真);        的emailList =新的JTable();
        注销=的新的JButton(注销);
        logout.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==注销){
                    新textEmailLog();
                }
            }        });
        删除=的新的JButton(删除);
        delete.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==删除){                }
            }        });
        首页=新的JButton(主页);
        homepage.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==主页){
                    新的主页();
                }            }        });
        框horizo​​ntalContainer = Box.createHorizo​​ntalBox();
        框verticalContainer = Box.createVerticalBox();
        框mergerContainer = Box.createVerticalBox();        horizo​​ntalContainer.add(注销);
        horizo​​ntalContainer.add(Box.createHorizo​​ntalStrut(5));
        horizo​​ntalContainer.add(主页);
        horizo​​ntalContainer.add(Box.createHorizo​​ntalStrut(5));
        horizo​​ntalContainer.add(删除);
        horizo​​ntalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(的emailList);
        mergerContainer.add(horizo​​ntalContainer);
        mergerContainer.add(verticalContainer);
        加(mergerContainer);        调用setVisible(真);
    }
}

我的上传电子邮件面板

 进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;进口javax.swing.Box中;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.JTextArea中;
进口javax.swing.JTextField中;
公共类loadEmail继承JPanel {
        JPanel的loadPanel;
        JLabel的fileLab,toLab,fromLab,subjectLab,topicLab,emailLab,notesLab,attachLab;
        JTextField的FILETEXT,toText,fromText,subjectText,topicText;
        JTextArea中emailText,notesText,attachText; //附件的文本将被改变
        JButton的取消,完成后,进入; //进入可能没有必要
    公共loadEmail(){
        的setSize(700700);        fileLab =新的JLabel(输入新的文件:);
        FILETEXT =新的JTextField();
        输入=的新的JButton(回车);
        enter.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==进入){
                    //打开文件目录窗口
                }
            }        });
        toLab =新的JLabel(为:);
        toText =新的JTextField();
        toText.setSize(5,30);
        fromLab =新的JLabel(发件人);
        fromText =新的JTextField();
        subjectLab =新的JLabel(主题:);
        subjectText =新的JTextField();
        topicLab =新的JLabel(话题:);
        topicText =新的JTextField();
        emailLab =新的JLabel(邮件内容:);
        emailText =新的JTextArea();
        notesLab =新的JLabel(评论:);
        notesText =新的JTextArea();
        attachLab =新的JLabel(附件);
        attachText =新的JTextArea();
        取消=的新的JButton(取消);
        cancel.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==取消){
                    //配置页面
                }
            }        });
        完整=的新的JButton(完成);
        complete.addActionListener(新的ActionListener(){            公共无效的actionPerformed(ActionEvent的五){
                // TODO自动生成方法存根
                如果(e.getSource()==完成){
                    //存储数据库,新邮件提示用户在其他明智返回首页进入                }
            }        });        框verticalContainer = Box.createVerticalBox();
        框horizo​​ntalContainer = Box.createHorizo​​ntalBox();
        框mergerContainer = Box.createVerticalBox();        verticalContainer.add(fileLab);
        verticalContainer.add(FILETEXT);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(Box.createHorizo​​ntalStrut(50));
        verticalContainer.add(输入);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(toLab);
        verticalContainer.add(toText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(fromLab);
        verticalContainer.add(fromText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(subjectLab);
        verticalContainer.add(subjectText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(topicLab);
        verticalContainer.add(topicText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(emailLab);
        verticalContainer.add(emailText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(notesLab);
        verticalContainer.add(notesText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(attachLab);
        verticalContainer.add(attachText);
        verticalContainer.add(Box.createVerticalStrut(5));        horizo​​ntalContainer.add(取消);
        horizo​​ntalContainer.add(Box.createHorizo​​ntalStrut(5));
        horizo​​ntalContainer.add(完成);        mergerContainer.add(verticalContainer);
        mergerContainer.add(horizo​​ntalContainer);
        加(mergerContainer);
        调用setVisible(真);    }}


解决方案

简短的答案是没有。造成这种情况的原因是你最终不必暴露父容器和 CardLayout 所有的子组件,这不仅暴露了你的应用程序的某些部分潜在的虐待,它紧紧地夫妻使其难以在导航中添加/删除在未来的步骤...

有一个更好的解决办法是制定某种控制器接口,中定义每个视图可以做些什么(例如 showHome 新思维 previousView ),那么您需要通过这个接口的实现为每个视图。然后,每个视图将使用这个接口要求的需要发生了变化。

控制器会知道之类的东西,目前来看,主视图,以及如何某些视图之间切换(下一首/ previous)的要求。

更新与简单的例子

 进口java.awt.BorderLayout中;
进口java.awt.CardLayout中;
进口java.awt.Component中;
进口java.awt.Container中;
进口java.awt.EventQueue中;
进口java.awt.GridBagLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口java.awt.event.ComponentAdapter;
进口java.awt.event.ComponentEvent;
进口java.awt.event.ContainerAdapter;
进口java.awt.event.ContainerEvent;
进口java.awt.event.HierarchyEvent中;
进口java.awt.event.HierarchyListener;
进口java.beans.PropertyChangeEvent中;
进口的java.beans.PropertyChangeListener;
进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;
进口的java.util.Map;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.UIManager中;
进口javax.swing.UnsupportedLookAndFeelException;公共类AllYouViewBelongToMe {    公共静态无效的主要(字串[] args){
        新AllYouViewBelongToMe();
    }    公共AllYouViewBelongToMe(){
        EventQueue.invokeLater(新的Runnable(){
            @覆盖
            公共无效的run(){
                尝试{
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }赶上(ClassNotFoundException的| InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException前){
                }                JFrame的帧=新的JFrame(测试);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(新的BorderLayout());
                frame.add(新TestPane());
                frame.pack();
                frame.setLocationRelativeTo(NULL);
                frame.setVisible(真);
            }
        });
    }    公共接口ViewContoller {        公共无效GOHOME();        公共无效的新思维();        公共无效previousView();    }    公共静态类DefaultViewController实现ViewContoller {        公共静态最后弦乐HOME =家;        私有组件currentView = NULL;
        私人列表<成分>意见;
        私人地图<成分,字符串> mapNames;        私营集装箱父母;
        私人CardLayout cardLayout;        公共DefaultViewController(集装箱父母,CardLayout cardLayout){
            this.parent =父母;
            this.cardLayout = cardLayout;
            意见=新的ArrayList<>(25);
            mapNames =新的HashMap<>(25);
        }        公共CardLayout getCardLayout(){
            返回cardLayout;
        }        公共集装箱的getParent(){
            回到父母;
        }        公共无效addView(组件comp,字符串名称){
            如果(!HOME.equals(名称)){
                views.add(化合物);
            }
            mapNames.put(对比,名);
            。的getParent()加(对比,名);
        }        公共无效removeView(组件comp,字符串名称){
            views.remove(化合物);
            mapNames.remove(化合物);
            。的getParent()删除(COMP);
        }        @覆盖
        公共无效GOHOME(){
            currentView = NULL;
            getCardLayout()表演(的getParent(),HOME)。
        }        @覆盖
        公共无效的新思维(){
            如果(views.size()大于0){
                字符串名称= NULL;
                如果(currentView == NULL){
                    currentView = views.get(0);
                    名称= mapNames.get(currentView);
                }其他{
                    INT指数= views.indexOf(currentView);
                    指数++;
                    如果(索引> = views.size()){
                        索引= 0;
                    }
                    currentView = views.get(指数);
                    名称= mapNames.get(currentView);
                }
                getCardLayout()表演(的getParent(),名称)。
            }
        }        @覆盖
        公共无效previousView(){
            如果(views.size()大于0){
                字符串名称= NULL;
                如果(currentView == NULL){
                    currentView = views.get(views.size() - 1);
                    名称= mapNames.get(currentView);
                }其他{
                    INT指数= views.indexOf(currentView);
                    指数 -​​ ;
                    如果(指数℃下){
                        指数= views.size() - 1;
                    }
                    currentView = views.get(指数);
                    名称= mapNames.get(currentView);
                }
                getCardLayout()表演(的getParent(),名称)。
            }
        }    }    公共类TestPane继承JPanel {        公共TestPane(){
            的setLayout(新的BorderLayout());            CardLayout cardLayout =新CardLayout();
            观点的JPanel =新JPanel(cardLayout);            最后DefaultViewController控制器=新DefaultViewController(查看,cardLayout);
            controller.addView(createPane(家),DefaultViewController.HOME);
            controller.addView(createPane(页面#1),视图1);
            controller.addView(createPane(页#2),视图2);
            controller.addView(createPane(页面#3),VIEW3);
            controller.addView(createPane(页#4),View4);            controller.goHome();            JPanel的控制=新JPanel();
            JButton的BTN preV =的新的JButton(<);
            JButton的btnHome =的新的JButton(家);
            JButton的btnNext =的新的JButton(>中);            Controls.Add被(BTN preV);
            Controls.Add被(btnHome);
            Controls.Add被(btnNext);            btnNext.addActionListener(新的ActionListener(){
                @覆盖
                公共无效的actionPerformed(ActionEvent的五){
                    controller.nextView();
                }
            });
            BTN prev.addActionListener(新的ActionListener(){
                @覆盖
                公共无效的actionPerformed(ActionEvent的五){
                    。控制器previousView();
                }
            });
            btnHome.addActionListener(新的ActionListener(){
                @覆盖
                公共无效的actionPerformed(ActionEvent的五){
                    controller.goHome();
                }
            });            添加(视图);
            添加(对照组,BorderLayout.SOUTH);        }        受保护的JPanel createPane(字符串名称){            的JPanel面板=新JPanel(新的GridBagLayout());
            panel.add(新的JLabel(名));            返回面板;        }
    }}

I am new to using cardlayout and I have a few questions on how to implement it. I first would like to know the best way to implement cardlayout so that I can switch from panel to panel. My main question is how to use buttons inside the constructors of my panels to switch from panel to panel. I just started working on this project today so you will see some code that is not finished or that does not make sense. I first tried to make all my classes to extend JFrame but that led to multiple unwanted windows. If I can get some sort of example on how to effectively use cardlayout and how to switch panels using the buttons within my other panel constructors. My attempts on using cardlayout only worked for buttons that I created in my gui class however that is not the result I want. Please help if you can and thanks in advance.

This is my main class.

public class controller{
    public static void main(String[] args){

        new Gui();


    }
}

This is my gui class.

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Gui extends JFrame{
    homePage home = new homePage();
    public JPanel loginPanel = new textEmailLog(), 
    registerPanel = new Register(),
    homePanel = new homePage(), viewPanel  = new emailView(),
    loadPanel = new loadEmail(), contentPanel = new JPanel(new CardLayout());
    CardLayout cardLayout = new CardLayout();


    public Gui(){
        super("Email Database Program");
        setSize(700,700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPanel.setLayout(cardLayout);

        contentPanel.add(loginPanel, "Login");
        contentPanel.add(registerPanel, "Register");
        contentPanel.add(homePanel, "Home");
        contentPanel.add(viewPanel, "View");
        contentPanel.add(loadPanel, "Load");
        this.setContentPane(contentPanel);

        cardLayout.show(contentPanel, "Login");


        setVisible(true);


    }

My Login Panel class

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

//panel has been added
public class textEmailLog extends JPanel{
        JPanel logGui = null;
        JButton registerBut, logBut;
        JTextField Login;

    public textEmailLog(){
        //default characteristics
        setSize(700,700);
        setName("Email Database");
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        //Labels for username and password
        JLabel userLab = new JLabel("Username");
        JLabel pwLab = new JLabel("Password");

        //textfields for username and password
        Login = new JTextField("", 15);
        JPasswordField Password = new JPasswordField("", 15);
        Password.setEchoChar('*');

        //login button that confirms username and password
        logBut = new JButton("Login");
        logBut.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                //needs regex checks prior to logging in 

                if(e.getSource() == logBut){
                    /* Change the panel to the homepage
                    if(Login.getText().equals() && Password.getText().equals()){

                    }
                */  
                    new homePage();
                }


            }
        });

        registerBut = new JButton("Register");
        registerBut.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == registerBut){
                    //Change the panel to the register panel
                }
            }

        });

        //Box layout for organization of jcomponents
        Box verticalContainer = Box.createVerticalBox();
        Box horizontalContainer = Box.createHorizontalBox();
        Box mergerContainer = Box.createVerticalBox();


        //add to panel
        verticalContainer.add(Box.createVerticalStrut(300));//begin relative to the center
        verticalContainer.add(userLab);//Login label and text
        verticalContainer.add(Login);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(pwLab);//password label and text
        verticalContainer.add(Password);
        verticalContainer.add(Box.createVerticalStrut(5));
        horizontalContainer.add(registerBut);//register button
        horizontalContainer.add(Box.createHorizontalStrut(5));
        horizontalContainer.add(logBut);//login button

        //combines both the vertical and horizontal container
        mergerContainer.add(verticalContainer);
        mergerContainer.add(horizontalContainer);
        add(mergerContainer);
        //this.add(logGui);
        setVisible(true);

    }

}

My Register panel class

    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

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

    //No Panel addition
    public class Register extends JPanel{
            JButton submit, previous;
            JLabel firstLab, lastLab, userLab, passwordLab, repassLab, address, emailAdd, errorLabel;
            JTextField firstText, lastText, userText, addText, emailAddText;
            JPasswordField passwordText, repassText;

        public Register(){
            setSize(700,700);
            //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


            //register values and their labels and textfields
            firstLab = new JLabel("First Name: ");
            firstText = new JTextField("", 25);
            lastLab = new JLabel("Last Name: ");
            lastText = new JTextField("", 40);
            userLab = new JLabel("Username: ");
            userText = new JTextField("", 25);
            passwordLab = new JLabel("Password: ");
            passwordText = new JPasswordField("", 25);
            passwordText.setEchoChar('*');
            repassLab = new JLabel("Confirm Password");
            repassText = new JPasswordField("", 25);
            repassText.setEchoChar('*');
            address = new JLabel("Address: ");
            addText = new JTextField("", 50);
            emailAdd = new JLabel("Email Address: ");
            emailAddText = new JTextField("", 50);

            //error message for reigstration issues
            errorLabel = new JLabel();
            errorLabel.setForeground(Color.red);

            submit = new JButton("Submit");

            submit.addActionListener(new ActionListener(){

                @SuppressWarnings("deprecation")
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getSource() == submit){
                        //confirm with regex methods and if statements that have been created and need to be created
                        if(firstText.getText().length() == 0){
                            errorLabel.setText("*You have not entered a first name!");
                        }else
                        if(lastText.getText().length() == 0){
                            errorLabel.setText("*You have not entered a last name!");
                        }else
                        if(userText.getText().length() == 0){
                            errorLabel.setText("*You have not entered a username!");
                        }else
                        if(passwordText.toString().length() == 0){
                            errorLabel.setText("*You have not entered a Password!");
                        }else
                        if(repassText.toString().length() == 0){    
                            errorLabel.setText("*You have not matched your password!");
                        }
                        if(addText.getText().length() == 0){
                            errorLabel.setText("*You have not entered an address!");
                        }else
                        if(emailAddText.getText().length() == 0){
                            errorLabel.setText("*You have not entered an Email address!");
                        }else
                        if(userText.getText().length() < 8){
                            errorLabel.setText("*Username is too short!");
                        }
                        else
                        if(!(passwordText.toString().matches(repassText.toString()))){
                            errorLabel.setText("Passwords do not match!");
                        }
                        else
                        if(!isValidEmailAddress(emailAddText.getText())){
                            errorLabel.setText("*Invalid Email!");
                        }
                        else
                        if(!isValidAddress(addText.getText())){
                            errorLabel.setText("*Invalid Address!");
                        }
                    }
                }

            });
            //returns to the previous page
            previous = new JButton("Previous Page");
            previous.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getSource() == previous){
                        //card.show(login panel);
                    }
                }

            });
            Box verticalContainer = Box.createVerticalBox();
            Box horizontalContainer = Box.createHorizontalBox();
            Box mergerContainer = Box.createVerticalBox();

            verticalContainer.add(Box.createVerticalStrut(150));
            verticalContainer.add(firstLab);
            verticalContainer.add(firstText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(lastLab);
            verticalContainer.add(lastText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(userLab);
            verticalContainer.add(userText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(passwordLab);
            verticalContainer.add(passwordText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(repassLab); 
            verticalContainer.add(repassText);  
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(address); 
            verticalContainer.add(addText);
            verticalContainer.add(Box.createVerticalStrut(5));
            verticalContainer.add(emailAdd);
            verticalContainer.add(emailAddText);    
            verticalContainer.add(Box.createVerticalStrut(5));

            //horizontal
            verticalContainer.add(Box.createVerticalStrut(5));
            horizontalContainer.add(submit);
            horizontalContainer.add(Box.createHorizontalStrut(5));
            horizontalContainer.add(previous);

            //merger
            mergerContainer.add(verticalContainer);
            mergerContainer.add(horizontalContainer);

            add(mergerContainer);
            setVisible(true);
        }

        //regex check for valid Email
    public boolean isValidEmailAddress(String email){
            java.util.regex.Pattern p = java.util.regex.Pattern.compile("[A-Za-z0-9._\\%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}");
            java.util.regex.Matcher m = p.matcher(email);
            return m.matches();

        }
    //regex check for valid Address
    public boolean isValidAddress(String address){
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\d{1,3}.?\\d{0,3}\\s[a-zA-Z]{2,30}\\s[a-zA-Z]{2,15}");
        java.util.regex.Matcher m = p.matcher(address);
        return m.matches();

    }
    }

Homepage panel class

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

//NO Panel Yet
@SuppressWarnings("serial")
public class homePage extends JPanel{

        JButton uploadEmail, viewEmail;
    public homePage(){
        setSize(700,700);
        uploadEmail = new JButton("Upload Your Email");
        uploadEmail.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == uploadEmail){
                    new loadEmail();
                }
            }

        });
        viewEmail = new JButton("View An Email");
        viewEmail.addActionListener(new ActionListener(){       

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == viewEmail){
                    new emailView();
                }
            }

        });

        add(uploadEmail);
        add(viewEmail);
        setVisible(true);
    }
}

My View Email Panel

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class emailView extends JPanel{
        JPanel viewPanel;
        JButton logout, delete, homepage;
        JTable emailList;

        //Cannot be edited or may be in a new panel
        /*
        JLabel fileLab, toLab, fromLab, subjectLab,topicLab, emailLab, notesLab, attachLab;
        JTextField fileText, toText, fromText, subjectText, topicText;
        JTextArea emailText, notesText, attachText;
        */
    public emailView(){
        setSize(700,700);
        setVisible(true);

        emailList = new JTable();
        logout = new JButton("Logout");
        logout.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == logout){
                    new textEmailLog();
                }
            }

        });
        delete = new JButton("Delete");
        delete.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == delete){

                }
            }

        });
        homepage = new JButton("HomePage");
        homepage.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == homepage){
                    new homePage();
                }

            }

        });
        Box horizontalContainer = Box.createHorizontalBox();
        Box verticalContainer = Box.createVerticalBox();
        Box mergerContainer = Box.createVerticalBox();

        horizontalContainer.add(logout);
        horizontalContainer.add(Box.createHorizontalStrut(5));
        horizontalContainer.add(homepage);
        horizontalContainer.add(Box.createHorizontalStrut(5));
        horizontalContainer.add(delete);
        horizontalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(emailList);
        mergerContainer.add(horizontalContainer);
        mergerContainer.add(verticalContainer);
        add(mergerContainer);

        setVisible(true);
    }
}

My upload Email Panel

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class loadEmail extends JPanel{
        JPanel loadPanel;
        JLabel fileLab, toLab, fromLab, subjectLab, topicLab, emailLab, notesLab, attachLab;
        JTextField fileText, toText, fromText, subjectText, topicText;
        JTextArea emailText, notesText, attachText; //attachment text will be changed
        JButton cancel, complete, enter;//enter may not be necessary
    public loadEmail(){
        setSize(700,700);

        fileLab = new JLabel("Enter a new File: ");
        fileText = new JTextField();
        enter = new JButton("Enter");
        enter.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == enter){
                    //opens file directory window
                }
            }

        });
        toLab = new JLabel("To: ");
        toText = new JTextField();
        toText.setSize(5, 30);
        fromLab = new JLabel("From: ");
        fromText = new JTextField();
        subjectLab = new JLabel("Subject: ");
        subjectText = new JTextField();
        topicLab = new JLabel("Topic: ");
        topicText = new JTextField();
        emailLab = new JLabel("Email Content: ");
        emailText = new JTextArea();
        notesLab = new JLabel("Comments: ");
        notesText = new JTextArea();
        attachLab = new JLabel("Attachments");
        attachText = new JTextArea();
        cancel = new JButton("Cancel");
        cancel.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == cancel){
                    //dispose page
                }
            }

        });
        complete = new JButton("Complete");
        complete.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if(e.getSource() == complete){
                    //store in database, prompt user for new email to enter in other wise return to homepage

                }
            }

        });

        Box verticalContainer = Box.createVerticalBox();
        Box horizontalContainer = Box.createHorizontalBox();
        Box mergerContainer = Box.createVerticalBox();

        verticalContainer.add(fileLab);
        verticalContainer.add(fileText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(Box.createHorizontalStrut(50));
        verticalContainer.add(enter);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(toLab);
        verticalContainer.add(toText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(fromLab);
        verticalContainer.add(fromText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(subjectLab);
        verticalContainer.add(subjectText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(topicLab);
        verticalContainer.add(topicText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(emailLab);
        verticalContainer.add(emailText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(notesLab);
        verticalContainer.add(notesText);
        verticalContainer.add(Box.createVerticalStrut(5));
        verticalContainer.add(attachLab);
        verticalContainer.add(attachText);
        verticalContainer.add(Box.createVerticalStrut(5));

        horizontalContainer.add(cancel);
        horizontalContainer.add(Box.createHorizontalStrut(5));
        horizontalContainer.add(complete);

        mergerContainer.add(verticalContainer);
        mergerContainer.add(horizontalContainer);
        add(mergerContainer);
        setVisible(true);

    }

}

解决方案

The short answer is don't. The reasons for this is you'll end having to expose the parent container and CardLayout to ALL your sub components, which not only exposes portions of your application to potential mistreatment, it tightly couples the navigation making it difficult to add/remove steps in the future...

A better solution would be to devise some kind of controller interface, which defines what each view could do (for example showHome, nextView, previousView), you would then pass an implementation of this interface to each view. Each view would then use this interface to request a change as the needed to.

The controller would know things like, the current view, the home view and how to move between certain views (next/previous) as required.

Updated with simple example

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 AllYouViewBelongToMe {

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

    public AllYouViewBelongToMe() {
        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 interface ViewContoller {

        public void goHome();

        public void nextView();

        public void previousView();

    }

    public static class DefaultViewController implements ViewContoller {

        public static final String HOME = "home";

        private Component currentView = null;
        private List<Component> views;
        private Map<Component, String> mapNames;

        private Container parent;
        private CardLayout cardLayout;

        public DefaultViewController(Container parent, CardLayout cardLayout) {
            this.parent = parent;
            this.cardLayout = cardLayout;
            views = new ArrayList<>(25);
            mapNames = new HashMap<>(25);
        }

        public CardLayout getCardLayout() {
            return cardLayout;
        }

        public Container getParent() {
            return parent;
        }

        public void addView(Component comp, String name) {
            if (!HOME.equals(name)) {
                views.add(comp);
            }
            mapNames.put(comp, name);
            getParent().add(comp, name);
        }

        public void removeView(Component comp, String name) {
            views.remove(comp);
            mapNames.remove(comp);
            getParent().remove(comp);
        }

        @Override
        public void goHome() {
            currentView = null;
            getCardLayout().show(getParent(), HOME);
        }

        @Override
        public void nextView() {
            if (views.size() > 0) {
                String name = null;
                if (currentView == null) {
                    currentView = views.get(0);
                    name = mapNames.get(currentView);
                } else {
                    int index = views.indexOf(currentView);
                    index++;
                    if (index >= views.size()) {
                        index = 0;
                    }
                    currentView = views.get(index);
                    name = mapNames.get(currentView);
                }
                getCardLayout().show(getParent(), name);
            }
        }

        @Override
        public void previousView() {
            if (views.size() > 0) {
                String name = null;
                if (currentView == null) {
                    currentView = views.get(views.size() - 1);
                    name = mapNames.get(currentView);
                } else {
                    int index = views.indexOf(currentView);
                    index--;
                    if (index < 0) {
                        index = views.size() - 1;
                    }
                    currentView = views.get(index);
                    name = mapNames.get(currentView);
                }
                getCardLayout().show(getParent(), name);
            }
        }

    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());

            CardLayout cardLayout = new CardLayout();
            JPanel view = new JPanel(cardLayout);

            final DefaultViewController controller = new DefaultViewController(view, cardLayout);
            controller.addView(createPane("home"), DefaultViewController.HOME);
            controller.addView(createPane("Page #1"), "View1");
            controller.addView(createPane("Page #2"), "View2");
            controller.addView(createPane("Page #3"), "View3");
            controller.addView(createPane("Page #4"), "View4");

            controller.goHome();

            JPanel controls = new JPanel();
            JButton btnPrev = new JButton("<");
            JButton btnHome = new JButton("Home");
            JButton btnNext = new JButton(">");

            controls.add(btnPrev);
            controls.add(btnHome);
            controls.add(btnNext);

            btnNext.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    controller.nextView();
                }
            });
            btnPrev.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    controller.previousView();
                }
            });
            btnHome.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    controller.goHome();
                }
            });

            add(view);
            add(controls, BorderLayout.SOUTH);

        }

        protected JPanel createPane(String name) {

            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(new JLabel(name));

            return panel;

        }
    }

}

这篇关于如何有效利用cardlayout在java中,以各种面板的构造函数内使用面板按键切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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