簡體   English   中英

JFrame中的JButton不起作用

[英]JButton in JFrame does not work

我目前正在NetBeans中從事一個簡單的項目,已經習慣了JFrame Form。 我創建了幾個JFrames,我想通過按一下按鈕來跳過它們,但是每當我按下一個按鈕時,都不會發生任何事情。

這是我的代碼

public class MainLogIn extends javax.swing.JFrame {

/**
 * Creates new form MainLogIn
 */

//testdata
private String[] dummy_data = {"user1:parola1", "user2:parola2"};

public MainLogIn() {
    initComponents();

    LogIn = new JButton();
    signUp = new JButton();
    username = new JTextField();
    password = new JPasswordField();

    wrong = new JLabel();
    wrong.setVisible(false);
}

/**
 * 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();
    jLabel2 = new javax.swing.JLabel();
    username = new javax.swing.JTextField();
    password = new javax.swing.JPasswordField();
    LogIn = new javax.swing.JButton();
    signUp = new javax.swing.JButton();
    wrong = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Username:");

    jLabel2.setText("Password:");

    LogIn.setText("LogIn");
    LogIn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            LogInActionPerformed(evt);
        }
    });

    signUp.setText("SignUp");
    signUp.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            signUpActionPerformed(evt);
        }
    });

    wrong.setText("Wrong Username And Password");
    wrong.setVisible(false);

    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(16, 16, 16)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(31, 31, 31)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(username, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                        .addComponent(password)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(28, 28, 28)
                    .addComponent(LogIn)
                    .addGap(95, 95, 95)
                    .addComponent(signUp))
                .addGroup(layout.createSequentialGroup()
                    .addGap(60, 60, 60)
                    .addComponent(wrong)))
            .addContainerGap(146, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(51, 51, 51)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(52, 52, 52)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(LogIn)
                .addComponent(signUp))
            .addGap(26, 26, 26)
            .addComponent(wrong)
            .addContainerGap(48, Short.MAX_VALUE))
    );

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

private boolean isPasswordValid(String password)
{
    if(password.length()>8)
        return true;
    else
        return false;
}

private boolean loginAttempt(String user, String pass){

    String usertext, passtext;

    //get username and password
    usertext = user;
    passtext = pass;

    //check username
    if(usertext == null)
    {
        username.setText("Please add username");
    }
    if(passtext == null)
    {
        password.setText("Please add password");
    }
    else
        if(isPasswordValid(passtext) == false)
            password.setText("Password too short");

    //check for good data among dummy_data
    for(String credentials:dummy_data)
    {
        String[] user_pass = credentials.split(":");
        if(user_pass[0].equals(usertext) &&
           user_pass[1].equals(passtext))
            {
                return true;
            }
    }

    return false;
}


private void LogInActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    String usertext, passtext;
    usertext = username.getText().toString();
    passtext = password.getText().toString();
    if(loginAttempt(usertext,passtext) == true)
    { 
        LogIn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae) {
                WelcomeToTheServer view = new WelcomeToTheServer();
                view.setVisible(true);
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });
    }
    else
    {
        wrong.setVisible(true);
    }

}                                     

private void signUpActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // start NewUser JFrame
     signUp.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae) {
                NewUser new_userjframe = new NewUser();
                new_userjframe.setVisible(true);
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });
}                                      

/**
 * @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(MainLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainLogIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainLogIn.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 MainLogIn().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton LogIn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPasswordField password;
private javax.swing.JButton signUp;
private javax.swing.JTextField username;
private javax.swing.JLabel wrong;
// End of variables declaration                   

}

當我嘗試

LogIn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae) {
                WelcomeToTheServer view = new WelcomeToTheServer();
                view.setVisible(true);
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });

nothig發生了。 我把ActionListener寫錯了嗎?

謝謝

您將初始化LogIn (和其他組件)兩次,導致第二次覆蓋您已經設置的內容

首先是initialiseComponents() ,其次是返回時


通過將MainLogIn()構造函數更新為:

public MainLogIn() {
    initComponents();
}

您可以刪除重復項和問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM