窗口在点击按钮时未关闭。

huangapple go评论84阅读模式
英文:

Frame not closing when button is clicked

问题

我正在处理一个登录页面,这是我的 Java 项目,在登录页面上,用户可以选择创建一个新账户,如果他还没有。我成功地在按钮被点击时打开了创建账户的窗口,您可以在下面的代码中看到,但是当点击创建账户按钮时,我无法关闭登录的 JFRAME。在 Netbeans 的设计视图中,我将窗口的属性更改为 DISPOSE_ON_CLOSE,但仍然没有任何反应。请告诉我为什么会这样,您可以参考函数 "CreateAccountNowButtonActionPerformed"。

package pleasework;

import javax.swing.JFrame;

/**
 * This class represents the login form.
 */
public class login extends javax.swing.JFrame {
    
    public login() {
        initComponents();
    }
    
    private void initComponents() {
        // ... (其他组件的初始化代码)

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
        // ... (其他布局和组件代码)
    }
    
    private void CreateAccountNowButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        registration reg = new registration();
        reg.setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }                                                      
    
    public static void main(String args[]) {
        /* 设置外观 */
        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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        /* 创建并显示窗口 */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new login().setVisible(true);
            }
        });
    }
    
    // ... (其他变量声明)
}

请注意,代码中的 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);CreateAccountNowButtonActionPerformed 方法中被调用,这会尝试关闭当前的登录窗口。如果这不起作用,可能有其他原因导致窗口无法关闭,可能需要进一步的调试来解决问题。

英文:

I am working on a login page that is my java project and on the login page, the user can choose to create a new account if he hasn't. I managed to open the create account frame when the button is clicked if you see the code below but I cannot close the login JFRAME when the create account button is clicked. In the design view of netbeans, I changed the property of the frame to DISPOSE_ON_CLOSE and nothing is happening still. Do let me know of the why is this so, you can refer to the function "CreateAccountNowButtonActionPerformed"

package pleasework;
import javax.swing.JFrame;
/**
*
* @author jacksonseow
*/
public class login extends javax.swing.JFrame {
/*Creates new form login*/
public login() {
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() {
mainLabel = new javax.swing.JLabel();
usernameLabel = new javax.swing.JLabel();
txtUsername = new javax.swing.JTextField();
passwordLabel = new javax.swing.JLabel();
txtPassword = new javax.swing.JTextField();
LoginButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
CreateAccountNowButton = new javax.swing.JButton();
dealLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setBackground(new java.awt.Color(102, 102, 102));
setPreferredSize(new java.awt.Dimension(650, 380));
mainLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
mainLabel.setForeground(new java.awt.Color(255, 255, 255));
mainLabel.setText("Gracious Givers");
usernameLabel.setText("Username");
txtUsername.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtUsernameActionPerformed(evt);
}
});
passwordLabel.setText("Password");
txtPassword.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPasswordActionPerformed(evt);
}
});
LoginButton.setText("Login");
LoginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(51, 102, 255));
jLabel1.setText("OR");
CreateAccountNowButton.setText("Create Account Now!");
CreateAccountNowButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreateAccountNowButtonActionPerformed(evt);
}
});
dealLabel.setIcon(new javax.swing.ImageIcon("/Users/jacksonseow/Netbeans Images/deal.png")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(usernameLabel, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtUsername)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(221, 221, 221)
.addComponent(CreateAccountNowButton, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(229, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(307, 307, 307)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(253, 253, 253)
.addComponent(dealLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(231, 231, 231)
.addComponent(mainLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(244, 244, 244)
.addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(mainLabel)
.addGap(18, 18, 18)
.addComponent(dealLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(usernameLabel)
.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passwordLabel))
.addGap(18, 18, 18)
.addComponent(LoginButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CreateAccountNowButton)
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>                        
private void txtUsernameActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
}                                           
private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
}                                           
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
}                                           
private void CreateAccountNowButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
registration reg = new registration();
reg.setVisible(true);
//reg.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}                                                      
/**
* @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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.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 login().setVisible(true);
}
});
}
// Variables declaration - do not modify                     
private javax.swing.JButton CreateAccountNowButton;
private javax.swing.JButton LoginButton;
private javax.swing.JLabel dealLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel mainLabel;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUsername;
private javax.swing.JLabel usernameLabel;
// End of variables declaration                   
}

答案1

得分: 2

  1. 使用 JPasswordField 代替 JTextField 来输入密码。
  2. 比起创建自己的 JFrame,更好的选择是构建一个 JPanel,将所有控件放在上面(不包括 "ok-cancel"),然后使用 JOptionPane.showConfirmMessage(...) 方法传入你的 JPanel。这样做,"ok-cancel" 按钮会自动为你处理。
英文:

A couple of things:

  1. Use a JPasswordField instead of a JTextField for the password
  2. A better option than creating your own JFrame would be to just build a JPanel with all of your controls (minus "ok-cancel") and use JOptionPane.showConfirmMessage(...) with your JPanel. Doing this, the ok-cancel buttons are automatically handled for you.

答案2

得分: 0

在这里,当前的JFrame没有关闭,因为您没有给出关闭它的命令。

在CreateAccountNowButtonActionPerformed()方法中,您创建了一个注册JFrame的实例并设置其可见。因此,它将显示'reg' JFrame。但是,通过这个操作,您应该编写

setVisible(false);

而不是

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)执行的操作与您在设计视图中所做的操作相同。由于方法名不言自明,它设置默认的关闭操作,可以是不执行任何操作、隐藏此JFrame、释放它或退出程序。但是,为了应用该操作,我们需要调用使用此属性的某个函数。而这个函数就是setVisible(false)。

当您使用这个方法时,将使用您在框架属性中提到的默认关闭操作。

因此,保持设计视图中的属性不变,只需将这一行

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

替换为

setVisible(false);

就会实现所需的功能。在进行了这个更改之后,当您运行代码并点击按钮时,它将打开注册JFrame并关闭当前JFrame。

关于代码的一些建议:在其他答案中已经提到了一个点,即对于密码,您应该使用JPasswordField而不是JTextField。请遵循同样的做法。此外,最好的做法是使用以大写字母开头的类名。您应该在登录和注册类名中都遵循相同的做法。

英文:

Here, the current JFrame is not closing because you have not given the command to do so.

In the CreateAccountNowButtonActionPerformed() method, you are creating an instance of the registration JFrame and setting it visible. So, it will show 'reg' JFrame. But, with this operation, you should have written

setVisible(false);

instead of

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) does the same thing as you have done using the design view. As the method name is self-explanatory, it sets the default close operation, where it is to do nothing or to hide this JFrame or to dispose it or to exit the program. But, in order to apply that action, we need to call some function that uses this property. And this function is setVisible(false).

When you use this method, the default close operation that you have mentioned in the frame property, that will be used.

So, keep the property in the design view as it is, just change the line

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

to

setVisible(false);

and it will do the desired work. After this change when you run the code and press on the button, it will open the registration JFrame and close current JFrame.

Some advice related to the code : There is one point already mentioned in the other answer that for password you should use JPasswordField and not JTextField. Do follow the same thing. Also, it is better practice to write class name that starts with a captial letter. You should apply the same in both login and registration class names.

huangapple
  • 本文由 发表于 2020年7月28日 21:50:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63135697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定