[英]How to close JFrame without closing another
我知道這個問題已被多次解決,但我已盡一切努力使其正常工作。 首先,當用戶登錄合法時,我創建了一個 JDialog 作為我的加載彈出窗口。 然后我創建一個定時器來自動關閉框架,然后我的主菜單出現。 但是,我的主菜單也正在關閉。 我也將 defaultCloseOperation 設置為 DO NOTHING ON CLOSE。
登錄表單
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作為彈窗加載
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
}
主菜單
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
}
這個...
LoginForm exit = new LoginForm();
exit.dispatchEvent(new WindowEvent(exit, WindowEvent.WINDOW_CLOSING));
完全沒有意義,您在此處創建的LoginForm
實例與之前創建的實例無關,事實上, Loading
不負責管理它,它超出了 scope。
一個簡單的解決方案是使用“觀察者模式”,這樣當Loading
實際完成時,它可以通知任何相關方,他們可以處理下一步應該做什么。
例如...
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();
}
然后在你的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);
}
哦,你真的,真的需要看看如何使用按鈕、復選框和單選按鈕以及如何編寫一個動作監聽器,再次停止使用表單編輯器,它對你沒有任何好處
然而,奇怪的是,由於您使用的是模態對話框,您可以簡單地做...
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);
}
並獲得相同的效果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.