【问题标题】:How to pass from one GUI class to another GUI class?如何从一个 GUI 类传递到另一个 GUI 类?
【发布时间】:2015-11-09 19:58:46
【问题描述】:

这是我的 LoginGUI 类,我想从这个 GUI 类转移到另一个“StudentGUI”类。看起来很简单,但我想不通

    JButton btnNewButton_1 = new JButton("Log In");
    btnNewButton_1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

            if(Username.equals(textField1.getText())){

                    if(Password.equals(textField2.getText())){
                        // close(LoginGUI);
                        // run(StudentGUI); 

                    **Missing function**

                        msg = "Loged in!";
                    }else{
                        msg = "Login Denied";
                    }
                }else{
                    msg = "Login Denied";
                }   
                JOptionPane.showMessageDialog(null,msg);                    
            }




        });
    btnNewButton_1.setBounds(157, 230, 89, 23);
    frame.getContentPane().add(btnNewButton_1);
}

}

【问题讨论】:

  • 你需要有另一个 ui 的实例。如果没有其他类的更多代码,就不可能提供更多帮助。除此之外 - 在开始 UI 编程之前,尝试获取一本 java 基础书籍并了解面向对象编程
  • 我建议您使用CardLayout。使用多个 JFrame 是不好的做法。
  • 在您的具体情况下,您不需要。允许 UI 简单地充当从用户那里收集信息的机制,允许另一个类(控制器)确定当用户尝试验证其凭据时应该发生什么,并允许模型执行实际验证。验证后,单独的控制器将做出有关导航的决定。更多详情请见Model-View-Controller
  • 对于example

标签: java


【解决方案1】:

如果您想在多个视图之间切换,请使用CardLayout 这是一个简单的示例

package main.frames;

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

public class MainFrame extends JFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;

public MainFrame()
{
    JButton showOtherPanelBtn = new JButton("Show Other Panel");
    JButton backToHomeBtn = new JButton("Show Home Panel");

    cl = new CardLayout(5, 5);
    homeContainer = new JPanel(cl);
    homeContainer.setBackground(Color.black);

    homePanel = new JPanel();
    homePanel.setBackground(Color.blue);
    homePanel.add(showOtherPanelBtn);

    homeContainer.add(homePanel, "Home");

    otherPanel = new JPanel();
    otherPanel.setBackground(Color.green);
    otherPanel.add(backToHomeBtn);

    homeContainer.add(otherPanel, "Other Panel");

    showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
    backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));

    add(homeContainer);
    cl.show(homeContainer, "Home");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    setTitle("CardLayout Example");
    pack();
    setVisible(true);
}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(MainFrame::new);
}
}

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    相关资源
    最近更新 更多