简体   繁体   English

如何在不关闭另一个的情况下关闭 JFrame

[英]How to close JFrame without closing another

I know this question has been addressed many times, but I tried everything to make it work properly.我知道这个问题已被多次解决,但我已尽一切努力使其正常工作。 First and foremost, I create a JDialog as my loading pop-up when the user login is legitimate.首先,当用户登录合法时,我创建了一个 JDialog 作为我的加载弹出窗口。 Then I create a Timer to automatically dismiss the frame, and my main menu appears.然后我创建一个定时器来自动关闭框架,然后我的主菜单出现。 However, my main menu is also shutting.但是,我的主菜单也正在关闭。 I set the defaultCloseOperation to DO NOTHING ON CLOSE as well.我也将 defaultCloseOperation 设置为 DO NOTHING ON CLOSE。

LoginForm登录表单

public class LoginForm extends javax.swing.JFrame {

    /**
     * Creates new form LoginForm
     */
    public LoginForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        username = new javax.swing.JTextField();
        password = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        Login = new javax.swing.JLabel();
        labelpassword = new javax.swing.JLabel();
        labelusername = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Login.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        Login.setText("Login");
        Login.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
        Login.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LoginMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Login, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(Login, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
        );

        labelpassword.setText("Password");

        labelusername.setText("Username");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(143, 143, 143)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(username, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                                .addComponent(password))
                            .addComponent(labelpassword)
                            .addComponent(labelusername))))
                .addContainerGap(93, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(labelusername)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(labelpassword)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(64, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void LoginMouseClicked(java.awt.event.MouseEvent evt) {                                   
   Loading loading = new Loading(this, true);
   loading.setLocationRelativeTo(this);
   loading.setVisible(true);
    }                                  

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel Login;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelpassword;
    private javax.swing.JLabel labelusername;
    private javax.swing.JTextField password;
    private javax.swing.JTextField username;
    // End of variables declaration                   
}

JDialog as pop-up loading JDialog作为弹窗加载

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.Timer;
                                                                                                           

public class Loading extends javax.swing.JDialog {
  
    public Loading(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setBackground(new java.awt.Color(0, 0, 0, 0));
Timer timer = new Timer(10000, new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
        dispose();
     // I tried alrealdy to dispose the Login Form but doesn't working hence I will using this
     LoginForm exit = new LoginForm();
     exit.setVisible(true);
     exit.dispatchEvent(new WindowEvent(exit, WindowEvent.WINDOW_CLOSING));
     MainMenu menu = MainMenu();
     menu.setVisible(true);
    
    }
});
timer.setRepeats(false);
timer.start();    
           
        }
    /**
     * 
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        MainPanel = new javax.swing.JPanel();
        PleaseFIll = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);

        MainPanel.setBackground(new java.awt.Color(24, 25, 32));
        MainPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        PleaseFIll.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
        PleaseFIll.setForeground(new java.awt.Color(255, 255, 255));
        PleaseFIll.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        PleaseFIll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restaurantorderingandpayment/images/hourglass.gif"))); // NOI18N
        MainPanel.add(PleaseFIll, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 230, 60));

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restaurantorderingandpayment/images/loading.gif"))); // NOI18N
        MainPanel.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 230, 30));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(MainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Loading dialog = new Loading(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
              
           
                   
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel MainPanel;
    private javax.swing.JLabel PleaseFIll;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration                   
}

MainMenu主菜单

public class MainMenu extends javax.swing.JFrame {

    /**
     * Creates new form MainMenu
     */
    public MainMenu() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("WELCOME");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(171, 171, 171)
                .addComponent(jLabel1)
                .addContainerGap(172, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(131, 131, 131)
                .addComponent(jLabel1)
                .addContainerGap(154, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainMenu().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

This...这个...

LoginForm exit = new LoginForm();
exit.dispatchEvent(new WindowEvent(exit, WindowEvent.WINDOW_CLOSING));

makes no sense at all, the instance of LoginForm you've created here has nothing to do with the one which was created eailier, in fact, Loading has no responsibility for managing it, it's beyong it's scope.完全没有意义,您在此处创建的LoginForm实例与之前创建的实例无关,事实上, Loading不负责管理它,它超出了 scope。

A simple solution would be to make use of an "observer pattern", so that when Loading has actually completed, it can inform any intertested parties and they have can take care of what should be done next.一个简单的解决方案是使用“观察者模式”,这样当Loading实际完成时,它可以通知任何相关方,他们可以处理下一步应该做什么。

For example...例如...

public class Loading extends javax.swing.JDialog {

    public interface Observer {
        public void loadingDidComplete();
    }

    private Observer observer;

    public Loading(java.awt.Frame parent, Observer observer) {
        super(parent, true);
        this.observer = observer;
        initComponents();
        this.setBackground(new java.awt.Color(0, 0, 0, 0));
        Timer timer = new Timer(10000, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                observer.loadingDidComplete();
            }
        });
        timer.setRepeats(false);
        timer.start();

    }

And then in your LoginForm you could so something like...然后在你的LoginForm中你可以这样......

private void LoginMouseClicked(java.awt.event.MouseEvent evt) {
    Loading loading = new Loading(this, new Loading.Observer() {
        @Override
        public void loadingDidComplete() {
            dispose();
            JFrame frame = new MainMenu();
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    loading.setLocationRelativeTo(this);
    loading.setVisible(true);
}

Oh, and you really, really need to look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener , again, stop using the form editor, it's not doing your any favours哦,你真的,真的需要看看如何使用按钮、复选框和单选按钮以及如何编写一个动作监听器,再次停止使用表单编辑器,它对你没有任何好处

However, oddly enough, since you're using a modal dialog, you could simply do...然而,奇怪的是,由于您使用的是模态对话框,您可以简单地做...

private void LoginMouseClicked(java.awt.event.MouseEvent evt) {
    Loading loading = new Loading(this);
    loading.setLocationRelativeTo(this);
    loading.setVisible(true);

    dispose();
    JFrame frame = new MainMenu();
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

and get the same effect并获得相同的效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM