2013-12-12 4 views
0

У меня есть две проблемы сейчас. Моя первая проблема - когда я нажимаю кнопку подтверждения, она будет вставлять данные два раза в базу данных доступа MS. Моя вторая проблема - почему joptionpane также появляется дважды.Почему joptionpane popup два раза

У меня есть главная страница входа при открытии программы. Когда я нажимаю кнопку регистрации, он удаляет весь компонент внутри центра jpanel. Затем он добавит снова компонент для использования в регистрационной форме, например jtextfield, jlabel, значок для имени пользователя, пароля, tel no и других. Я уже проверил, что инструкция для выполнения инструкции insert и joptionpanes имеет только один раз.

Это полный код моей программы

package userForm; 

    import java.sql.*; 
    import java.util.logging.Handler; 
    import javax.swing.*; 
    import javax.swing.border.Border; 
    import javax.swing.border.EmptyBorder; 
    import java.awt.*; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 

    public class loginForm extends JFrame implements ActionListener{ 

    private JPanel centerPanel,bottomPanel; 
    private JLabel titleLabel, descriptionLabel; 
    private JLabel usernameLabel, passwordLabel, signInLabel, iconUsername, iconPassword; 
    private JLabel signUpLabel, fullNameLabel, staffIDLabel, usernameRegLabel, passwordRegLabel, telNoLabel, emailLabel; 
    private JLabel iconFullName, iconStaffID, iconUsernameReg, iconPasswordReg, iconTelNo, iconEmail; 
    private JTextField usernameField, fullNameField, staffIDField, usernameRegField, telNoField, emailField; 
    private JPasswordField passwordField, passwordRegField; 
    private JButton loginButton, signUpButton,confirmButton,exitButton; 
    private String username; 
    private String password; 
    userDatabase db; 
    userDatabase db1; 
    handler handle; 

    public loginForm(String title) { 

     db=new userDatabase(); 
     handle =new handler(); 

     //create label to use in topPanel 
     titleLabel = new JLabel("ABC Burger Inventory System"); 
     titleLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 23)); 
     titleLabel.setForeground(Color.white); 
     Border empty = new EmptyBorder(30, 20, 0, 0); 
     titleLabel.setBorder(empty); 
     descriptionLabel = new JLabel("Please Login To Use This System"); 
     Border empty1 = new EmptyBorder(-30, 20, 0, 0); 
     descriptionLabel.setBorder(empty1); 
     descriptionLabel.setFont(new Font("Calibri", Font.HANGING_BASELINE, 14)); 
     descriptionLabel.setForeground(Color.white); 

     //create label to use in centerPanel 
     signInLabel = new JLabel("SIGN IN"); 
     usernameLabel = new JLabel("Username:"); 
     passwordLabel = new JLabel("Password"); 

     //create textfield to use in center Panel 
     usernameField = new JTextField("Required"); 

     passwordField = new JPasswordField("Required"); 

     //create label to use in registration form 
     signUpLabel = new JLabel("SIGN UP"); 
     fullNameLabel = new JLabel("Full Name:"); 
     staffIDLabel = new JLabel("Staff ID:"); 
     usernameRegLabel = new JLabel("Username:"); 
     passwordRegLabel = new JLabel("Password"); 
     telNoLabel = new JLabel("Tel No:"); 
     emailLabel = new JLabel("Email:"); 

     //create textfield to use in registration form 
     fullNameField = new JTextField(30); 
     staffIDField = new JTextField(30); 
     usernameRegField = new JTextField(30); 
     passwordRegField = new JPasswordField(30); 
     telNoField = new JTextField(30); 
     emailField = new JTextField(30); 


     //create button to use in bottom Panel 
     loginButton = new JButton("Login"); 
     signUpButton = new JButton("Sign Up"); 
     confirmButton = new JButton("Confirm"); 
     confirmButton.addActionListener(this); 
     exitButton = new JButton("Exit"); 
     exitButton.addActionListener(this); 

     //create panel to use in frame 
     topPanelWithBackground topPanel = new topPanelWithBackground(); 
     topPanel.setLayout(new GridLayout(2,1)); 
     centerPanel = new JPanel(); 
     centerPanel.setLayout(null); 
     bottomPanel = new JPanel(); 
     bottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 10)); 

     //add component to top panel 
     topPanel.add(titleLabel); 
     topPanel.add(descriptionLabel); 

     //add component to center panel 
     signInLabel.setBounds(270, 30, 100, 20); 
     signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20)); 
     centerPanel.add(signInLabel); 

     usernameLabel.setBounds(200, 60, 100, 20); 
     usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
     centerPanel.add(usernameLabel); 

     ImageIcon imageUser = new ImageIcon("user.png"); 
     iconUsername = new JLabel(imageUser, JLabel.CENTER); 
     iconUsername.setBounds(160, 90, 32, 32); 
     centerPanel.add(iconUsername); 

     usernameField.setBounds(200, 90, 200, 32); 
     usernameField.setFont(new Font("Calibri", Font.BOLD, 14)); 
     centerPanel.add(usernameField); 

     passwordLabel.setBounds(200, 140, 100, 20); 
     passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
     centerPanel.add(passwordLabel); 

     ImageIcon imagePassword = new ImageIcon("password.png"); 
     iconUsername = new JLabel(imagePassword, JLabel.CENTER); 
     iconUsername.setBounds(160, 170, 32, 32); 
     centerPanel.add(iconUsername); 

     passwordField.setBounds(200, 170, 200, 32); 
     passwordField.setFont(new Font("Calibri", Font.BOLD, 14)); 
     centerPanel.add(passwordField); 

     loginButton.setFont(new Font("Calibri", Font.BOLD, 14)); 
     loginButton.addActionListener(handle); 
     bottomPanel.add(loginButton); 

     signUpButton.setFont(new Font("Calibri", Font.BOLD, 14)); 
     signUpButton.addActionListener(this); 
     bottomPanel.add(signUpButton); 

     //add confirm button 
     exitButton.setFont(new Font("Calibri", Font.BOLD, 14)); 
     exitButton.addActionListener(this); 
     bottomPanel.add(exitButton); 

     getContentPane().setLayout(new BorderLayout()); 
     getContentPane().add(topPanel, BorderLayout.NORTH); 
     getContentPane().add(centerPanel, BorderLayout.CENTER); 
     getContentPane().add(bottomPanel, BorderLayout.SOUTH); 


     //frame behaviour 
     super.setTitle(title); 
     setVisible(true); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit 
     setSize(600,500); 

    } 

     class handler implements ActionListener{ 
      public void actionPerformed(ActionEvent as) { 
       if(as.getSource()==loginButton){ 
        centerPanel.removeAll(); 
        centerPanel.revalidate(); 
        centerPanel.repaint(); 
        //add component to center panel 
        signInLabel.setBounds(270, 30, 100, 20); 
        signInLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20)); 
        centerPanel.add(signInLabel); 

        usernameLabel.setBounds(200, 60, 100, 20); 
        usernameLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
        centerPanel.add(usernameLabel); 

        ImageIcon imageUser = new ImageIcon("user.png"); 
        iconUsername = new JLabel(imageUser, JLabel.CENTER); 
        iconUsername.setBounds(160, 90, 32, 32); 
        centerPanel.add(iconUsername); 

        usernameField.setBounds(200, 90, 200, 32); 
        usernameField.setFont(new Font("Calibri", Font.BOLD, 14)); 
        centerPanel.add(usernameField); 

        passwordLabel.setBounds(200, 140, 100, 20); 
        passwordLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
        centerPanel.add(passwordLabel); 

        ImageIcon imagePassword = new ImageIcon("password.png"); 
        iconUsername = new JLabel(imagePassword, JLabel.CENTER); 
        iconUsername.setBounds(160, 170, 32, 32); 
        centerPanel.add(iconUsername); 

        passwordField.setBounds(200, 170, 200, 32); 
        passwordField.setFont(new Font("Calibri", Font.BOLD, 14)); 
        centerPanel.add(passwordField); 

        char[] temp_pwd=passwordField.getPassword(); 
        String pwd=null; 
        pwd=String.copyValueOf(temp_pwd); 
        System.out.println("Username,Pwd:"+usernameField.getText()+","+pwd); 

        //The entered username and password are sent via "checkLogin()" which return boolean 
        if(db.checkLogin(usernameField.getText(), pwd)) 
        { 
         newFrame regFace =new newFrame(); 
         regFace.setVisible(true); 
         dispose(); 
        } 
        else if(usernameField.getText().equals("") || passwordField.getText().equals("")){ 
         JOptionPane.showMessageDialog(null, "Please fill out the form","Error!!", 
           JOptionPane.ERROR_MESSAGE); 
        } 
        else 
        { 
         //a pop-up box 
         JOptionPane.showMessageDialog(null, "Login failed!","Failed!!", 
              JOptionPane.ERROR_MESSAGE); 
        } 
       } 

      } 
      } 

     @Override 
     public void actionPerformed(ActionEvent ae) { 
      if(ae.getSource()==signUpButton){ 
       centerPanel.removeAll(); 
         //sign up label 
       signUpLabel.setBounds(270, 30, 100, 20); 
       signUpLabel.setFont(new Font("Calibri", Font.TRUETYPE_FONT, 20)); 
       centerPanel.add(signUpLabel); 

       //fullname label,icon and field 
       fullNameLabel.setBounds(80, 60, 100, 20); 
       fullNameLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(fullNameLabel); 

       ImageIcon imageFullname = new ImageIcon("fullname.png"); 
       iconUsernameReg = new JLabel(imageFullname, JLabel.CENTER); 
       iconUsernameReg.setBounds(40, 90, 32, 32); 
       centerPanel.add(iconUsernameReg); 

       fullNameField.setBounds(80, 90, 200, 32); 
       fullNameField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(fullNameField); 

       //staffID label,icon and field 
       staffIDLabel.setBounds(80, 140, 100, 20); 
       staffIDLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(staffIDLabel); 

       ImageIcon imageStaffID = new ImageIcon("staffID.png"); 
       iconStaffID = new JLabel(imageStaffID, JLabel.CENTER); 
       iconStaffID.setBounds(40, 170, 32, 32); 
       centerPanel.add(iconStaffID); 

       staffIDField.setBounds(80, 170, 200, 32); 
       staffIDField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(staffIDField); 

       //usernameReg label,icon and field   
       usernameRegLabel.setBounds(80, 220, 100, 20); 
       usernameRegLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(usernameRegLabel); 

       ImageIcon imageUsernameReg = new ImageIcon("user.png"); 
       iconUsernameReg = new JLabel(imageUsernameReg, JLabel.CENTER); 
       iconUsernameReg.setBounds(40, 250, 32, 32); 
       centerPanel.add(iconUsernameReg); 

       usernameRegField.setBounds(80, 250, 200, 32); 
       usernameRegField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(usernameRegField); 

       //passwordReg label,icon and field   
       passwordRegLabel.setBounds(350, 60, 100, 20); 
       passwordRegLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(passwordRegLabel); 

       ImageIcon imagePasswordReg = new ImageIcon("password.png"); 
       iconPasswordReg = new JLabel(imagePasswordReg, JLabel.CENTER); 
       iconPasswordReg.setBounds(310, 90, 32, 32); 
       centerPanel.add(iconPasswordReg); 

       passwordRegField.setBounds(350, 90, 200, 32); 
       passwordRegField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(passwordRegField); 

       //telNo label,icon and field    
       telNoLabel.setBounds(350, 140, 100, 20); 
       telNoLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(telNoLabel); 

       ImageIcon imagetelNo = new ImageIcon("phone.png"); 
       iconTelNo = new JLabel(imagetelNo, JLabel.CENTER); 
       iconTelNo.setBounds(310, 170, 32, 32); 
       centerPanel.add(iconTelNo); 

       telNoField.setBounds(350, 170, 200, 32); 
       telNoField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(telNoField); 

       //Email label,icon and field    
       emailLabel.setBounds(350, 220, 100, 20); 
       emailLabel.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(emailLabel); 

       ImageIcon imageEmail = new ImageIcon("mail.png"); 
       iconEmail = new JLabel(imageEmail , JLabel.CENTER); 
       iconEmail .setBounds(310, 250, 32, 32); 
       centerPanel.add(iconEmail); 

       emailField.setBounds(350, 250, 200, 32); 
       emailField.setFont(new Font("Calibri", Font.BOLD, 14)); 
       centerPanel.add(emailField); 

       //add confirm button 
       confirmButton.setFont(new Font("Calibri", Font.BOLD, 14)); 
       confirmButton.addActionListener(this); 
       bottomPanel.add(confirmButton);  

       centerPanel.revalidate(); 
       centerPanel.repaint(); 

      } 
      else if(ae.getSource()==confirmButton){ 
       char[] temp_pwd1=passwordRegField.getPassword(); 
       String pwd=null; 
       pwd=String.copyValueOf(temp_pwd1); 
       if(fullNameField.getText().equals("") || staffIDField.getText().equals("") || usernameRegField.getText().equals("") || passwordRegField.getPassword().length == 0 || telNoField.getText().equals("") || emailField.getText().equals("")){ 
        JOptionPane.showMessageDialog(null, "Please Fill Out Any Field", "Error", 
          JOptionPane.ERROR_MESSAGE); 
       } 
       else { 
       db1 = new userDatabase(); 
       try { 
        db1.insertData(fullNameField.getText(), staffIDField.getText(), usernameRegField.getText(), pwd, telNoField.getText(), emailField.getText()); 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       } 
      } 
      else if(ae.getSource()==exitButton){ 
       System.exit(0); 
      } 
     } 

} 
+0

Слишком долго для предварительного просмотра. Я предполагаю, что есть ошибка логического потока, но ваш код не облегчает из-за кучки классов, которые вы определили в традиционно некорректном формате 'userDatabase', а не' UserDatabase'. Я бы порекомендовал вам использовать отладку Java и шаг за шагом. Похоже, что ваши действия дважды стреляют, когда они должны стрелять один раз, из-за того, что все происходит дважды. Смотрите, где что-то срабатывает, и почему он повторяет триггер. – Compass

+0

Не используйте setBounds() !!! Swing был разработан для использования с менеджерами компоновки. Не создавайте новый шрифт каждый раз. Создайте шрифт один раз, а затем добавьте один и тот же шрифт к каждому компоненту. – camickr

+0

@Compass, спасибо за советы от моего кода. Я буду следовать вашим советам. – cupin06

ответ

2

При нажатии на кнопку регистрации вы добавляете слушателю кнопку подтверждения еще раз. Поэтому, когда вы нажимаете кнопку подтверждения, она выполняется дважды.

Удалить следующую строку в методе actionPerformed из LoginForm

confirmButton.addActionListener(this); 
+0

tq..отправить проблему сейчас – cupin06

Смежные вопросы