【问题标题】:Implementing CardLayout within a JFrame and switching cards based on specific button presses在 JFrame 中实现 CardLayout 并根据特定按钮按下切换卡片
【发布时间】:2015-12-06 02:45:07
【问题描述】:

我在下面发布了我的代码。我有创建可导航 GUI 的简单任务。在过去的几个小时里,我一直在研究如何做到这一点,这就是我整理的代码。

最初我想在没有任何布局或任何东西的情况下执行导航。我需要在用户单击欢迎面板上的“登录”按钮后显示主页面板。

它很好地显示了欢迎卡,但是当我使用 validateLogin 方法(按下登录按钮时激活,成功登录后它应该在卡中显示主面板)它只是停留在欢迎面板上即使我已经验证我的程序通过 system.out.Println() 到达循环以更换卡片

请帮忙。我整个周六都在尝试通过试验和研究来解决这个问题,但没有成功。这对我来说是最后的手段,所以如果有人能向我展示我的缺陷,那么我会很高兴地去修复它。然后将该修复程序应用于我的程序所需的许多其他卡。

    enter code here
    public class mainGUI implements ActionListener{
JFrame main;
JPanel cards = new JPanel(new CardLayout());
CardLayout cl = (CardLayout)(cards.getLayout());

//Items for the welcome panel
JPanel welcome = welcomePanel();
JButton login;
JButton register;
JTextField username;
JTextField password;

//home panel
JPanel home = homePanel();


//WelcomePanel welcome = new WelcomePanel();

ArrayList<Student> students = new ArrayList<Student>();
Student workingStudent;


/**
 * calls load() at start and save() on exit
 * 
 */
public mainGUI(){
    load();

    main = new JFrame();
    main.setSize(900, 600);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setTitle("MyCourses 2k16");
    main.setContentPane(welcomePanel());

    //fill out the cards
    cards.add(welcome, "Welcome");
    cards.add(home, "Home");
            //display welcome card
    cl.show(cards, "welcome");

    main.setVisible(true);

    saveState();
}

private JPanel welcomePanel() {
    JPanel welcome = new JPanel();
    welcome.setLayout(null);
    welcome.setBackground(Color.DARK_GRAY);

    JLabel hi = new JLabel("Welcome to MyCourses 2K16");
    hi.setSize(800, 100);
    hi.setLocation(50,50);
    hi.setFont(new Font("Serif", Font.BOLD, 48));
    hi.setForeground(Color.WHITE);

    JLabel select = new JLabel("Fill in the information, then click login or register to proceed, no special characters allowed");
    select.setSize(700,100);
    select.setLocation(75,100);
    select.setFont(new Font("Serif", Font.PLAIN, 18));
    select.setForeground(Color.WHITE);

    login = new JButton( "login");
    login.setSize(100, 50);
    login.setLocation(50, 200);
    login.addActionListener(this);

    register = new JButton( "register");
    register.setSize(100,50);
    register.setLocation(200, 200);
    register.addActionListener(this);

    JLabel un = new JLabel("username");
    un.setSize(100, 30);
    un.setLocation(50, 270);
    un.setForeground(Color.WHITE);

    username = new JTextField();
    username.setSize(200, 30);
    username.setLocation(50,300);

    JLabel pw = new JLabel("password");
    pw.setSize(100, 30);
    pw.setLocation(50, 350);
    pw.setForeground(Color.WHITE);

    password = new JTextField();
    password.setSize(200, 30);
    password.setLocation(50,380);

    welcome.add(hi);
    welcome.add(select);
    welcome.add(login);
    welcome.add(register);
    welcome.add(un);
    welcome.add(username);
    welcome.add(pw);
    welcome.add(password);

    return welcome;
}

private JPanel homePanel() {
    JPanel home = new JPanel();
    home.setLayout(null);
    home.setBackground(Color.DARK_GRAY);

    JLabel hi = new JLabel("HOME");
    hi.setSize(800, 100);
    hi.setLocation(50,50);
    hi.setFont(new Font("Serif", Font.BOLD, 48));
    hi.setForeground(Color.WHITE);

    return home;

}

public void load(){

}

private void saveState(){
    Iterator<Student> it = students.iterator();
    while(it.hasNext()){
        it.next().saveStudent();
    }
}



public static void main(String[] args) {

    new mainGUI();

}


@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource()==login){
        System.out.println("Logging in...");
        validateLogin(students);
    }
    else if (e.getSource()==register){

    }
}

private void validateLogin(ArrayList<Student> students){
    boolean valid = false;

    for(int i = 0; i < students.size(); i++){

        if(username.getText().equals(students.get(i).getUsername())
                && password.getText().equals(students.get(i).getPassword()))
        {   
            valid = true;
            workingStudent=(students.get(i));
            System.out.println("Successful Login!");
            cl.show(cards, "home");
        }
    }
    if(valid == false){
        System.out.println("Invalid Login, try again");
    }

}

}

【问题讨论】:

  • I spent my entire Saturday trying to solve this one problem - 那么为什么在进行任何测试之前要编写数百行代码呢?你为什么不从简单的东西开始,比如带按钮的面板。当您单击该按钮时,您将切换到第二个面板。然后该面板还有一个按钮可以切换回第一个面板。该代码将是 20-30 行代码,很容易找到您的错误。然后,一旦您了解了交换面板的基本概念,您就可以为每个面板添加更多组件/逻辑。
  • 好吧,伙计,非常感谢,你明白了。这非常有帮助....自我说明:测试你不理解的东西
  • note to self: TEST STUFF YOU DONT UNDERSTAND - 完全正确。编写一个 20-30 行的简短程序来测试一个新概念。然后,如果它不起作用,您可以在论坛中发布一些简单的内容。为什么你希望我们通读 100 行代码来找出你可能犯的一个错误???合乎逻辑。在跑步之前学会走路,这样你就不会浪费一整个晚上来解决你的问题。解决问题是你需要学习的技能。简化问题将大有帮助。
  • 好的,这里有一些简单的好东西。我的代码中的一切都有效。我知道,因为我一直在测试,一步一步....现在我已经到了无法让家庭卡显示的地步。这是我的简单问题。我只想知道为什么我不能显示主卡。
  • 你为什么希望我通读 100 行我通常不理解的其他人的代码,然后将其转化为适用于我的特定问题的可用信息。

标签: java swing jframe jpanel cardlayout


【解决方案1】:

您创建了一个使用 CardLayout、卡片的 JPanel,但是您将它添加到任何内容中,因此它当然不会显示自己,也不会显示它的卡片。解决方案:将此 JPanel 添加到您的 GUI。

所以而不是:

main.setContentPane(welcomePanel());

做:

main.setContentPane(cards);

问题编号 2:

使用字符串作为键类型时使用字符串常量。请注意,您将一个 JPanel 添加到卡片 JPanel 中:

cards.add(home, "Home");

然后尝试像这样显示它:

cl.show(cards, "home");

但家不等于家。

改为声明一个常量 HOME:

public static final String HOME = "home";

并使用相同的常量来添加 JPanel 并显示它。

举个简单的例子:

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

import javax.swing.*;

public class MainGui2 extends JPanel {
    private CardLayout cardLayout = new CardLayout();
    private WelcomePanel welcomePanel = new WelcomePanel(this);
    private HomePanel homePanel = new HomePanel();

    public MainGui2() {
        setLayout(cardLayout);
        add(welcomePanel, WelcomePanel.NAME);
        add(homePanel, HomePanel.NAME);
    }

    public void showCard(String name) {
        cardLayout.show(this, name);
    }

    private static void createAndShowGui() {
        MainGui2 mainPanel = new MainGui2();

        JFrame frame = new JFrame("MainGui2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

}

class WelcomePanel extends JPanel {
    public static final String NAME = "welcome panel";
    private MainGui2 mainGui2;

    public WelcomePanel(final MainGui2 mainGui2) {
        this.mainGui2 = mainGui2;
        add(new JLabel(NAME));
        add(new JButton(new AbstractAction("Logon") {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainGui2.showCard(HomePanel.NAME);
            }
        }));
    }
}

class HomePanel extends JPanel {
    public static final String NAME = "home panel";

    public HomePanel() {
        add(new JLabel(NAME));
    }
}

【讨论】:

  • @Nasmarr:见编辑。并听听 camickr 怎么说——不断调试。与其嘲笑他,不如学会欣赏他的智慧——我是根据经验说话,因为这样做教会了我很多。
  • @Nasmarr:请参阅编辑以了解我的意思的简单示例。
  • 或者您可以阅读 How to Use a CardLayout 上的 Swing 教程。它不仅有用于 CardLayout 的工作代码,而且还有大量适用于所有 Swing 功能的工作示例。教程链接应该放在手边,因为它是一个很好的参考,在询问 Swing 相关问题之前应该先查阅它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 2017-06-10
  • 1970-01-01
  • 2023-03-26
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多