-1

I have 2 Swing developed applications. 1) Pay screen, in which, user id and 'pay' buttons will be there. 2) Another screen will have 'Match' button which checks for validity of user and returns respective user's password.

My main screen is 'Pay' screen. From here I will enter user id and click on 'Pay' button and it has to navigate to 'Another screen'. Up to here my code is working.

After doing validations in 'Match' button I should return password to 'Pay' screen. This portion of code is not working. Please help

 //Pay screen class
package trig_pack;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import java.awt.Image ;
import java.io.*; 
import java.sql.*;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import capture_match_finger_image.*;

public class trigPayClass extends javax.swing.JFrame {

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


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        t_userid = new javax.swing.JTextField();
        btn_pay = new javax.swing.JButton();
        lbl_result = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("User Id:");

        t_userid.setName("t_userid"); // NOI18N
        t_userid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                t_useridActionPerformed(evt);
            }
        });

        btn_pay.setText("PAY");
        btn_pay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_payActionPerformed(evt);
            }
        });

        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(44, 44, 44)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_pay)
                    .addComponent(t_userid, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_result, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(85, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(t_userid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btn_pay)
                .addGap(26, 26, 26)
                .addComponent(lbl_result, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(224, Short.MAX_VALUE))
        );

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

    private void btn_payActionPerformed(java.awt.event.ActionEvent evt) {                                        
        System.out.println("in btn_payActionPerformed");
        int v_userid=Integer.parseInt(t_userid.getText());
        System.out.println("v_userid-"+v_userid);
        Connection con=null;
                try
        {    

            con=DriverManager.getConnection(  
                         "<connection string>");  
            System.out.println("connection established..");
           fetchPasswordClass c=new fetchPasswordClass();   //another class
           String pwd=c.getpwd(v_userid,con); //call method in another class to get password fro incoming userid and connection objects
           lbl_result.setText(pwd);  //populate returned password in a label or text field. 
        } catch (Exception e) 
          { 
              e.printStackTrace(); 
          }
    }                                       

    private void t_useridActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    /**
     * @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 (javax.swing.UIManager.getSystemLookAndFeelClassName().equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(trigPayClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(trigPayClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(trigPayClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(trigPayClass.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 trigPayClass().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_pay;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lbl_result;
    private javax.swing.JTextField t_userid;
    // End of variables declaration                   
}

//Another screen

package match_pwd;

import java.awt.Color;
import java.awt.image.BufferedImage;  
import javax.swing.ImageIcon; 
import java.sql.*;
import javax.swing.JDialog; 
import javax.swing.JOptionPane;

public class fetchPasswordClass extends javax.swing.JFrame   {

    int v_userid=0;
    int v_nfiq=5;
    String match_result=null; 
    Connection i_con=null;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        btn_con = new javax.swing.JButton();
        pnl_srno = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        lbl_srno = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        lbl_nfiq = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        lbl_fing = new javax.swing.JLabel();
        lbl_stat = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btn_prv = new javax.swing.JButton();
        btn_match = new javax.swing.JButton();
        btn_disconn = new javax.swing.JButton();
        lbl_userid = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
        setBackground(new java.awt.Color(130, 140, 150));
        setMinimumSize(new java.awt.Dimension(613, 389));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btn_match.setText("MATCH");
        btn_match.setEnabled(false);
        btn_match.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_matchActionPerformed(evt);
            }
        });


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

    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
         //
    }                                  

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        // TODO add your handling code here:
    }            

    private String btn_matchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        System.out.println("In SaveActionPerformed");
        btn_match.setEnabled(false);
        if (lbl_userid.getText()!=null && lbl_userid.getText().length()>0)
        {
            System.out.println("Got Userid-"+v_userid);
            matchUserId m=new matchUserId();
            String match_success_yn=m.matchUser(v_userid);
            if (match_success_yn.equals("0"))
            { 
                match_result="Not valid user!";
            }
            else
            { 
                match_result=match_success_yn;
            }
        }
        else
        {
            System.out.println("Userid null");
            lbl_stat.setText("Please enter valid user id");
            btn_match.setEnabled(false); 
            match_result="Please pass valid user id";
        }
        return match_result;
    }                                         



    public String getpwd(int userid,Connection con){ 

        v_userid=userid; 
        System.out.println("v_userid- "+v_userid); 
        i_con=con;
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if (javax.swing.UIManager.getSystemLookAndFeelClassName().equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(fetchPasswordClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(fetchPasswordClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(fetchPasswordClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(fetchPasswordClass.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 fetchPasswordClass().setVisible(true); 

            initComponents();
            c.getContentPane().setBackground(new Color(176,176,176));//153, 255, 255  

            lbl_userid.setText(String.valueOf(v_userid)); 
            System.out.println(" lbl_userid.getText()- "+ lbl_userid.getText());         


             c.setVisible(true);

            }
        });
        System.out.println("before returning from matchclass");
       // return match_result; 
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_con;
    private javax.swing.JButton btn_disconn;
    private javax.swing.JButton btn_match;
    private javax.swing.JButton btn_prv;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbl_fing;
    private javax.swing.JLabel lbl_nfiq;
    private javax.swing.JLabel lbl_srno;
    private javax.swing.JLabel lbl_stat;
    private javax.swing.JLabel lbl_userid;
    private javax.swing.JPanel pnl_srno;
    // End of variables declaration                   

}
sai kiran
  • 1
  • 3
  • You need to make use of a dialog, which when presented will stop the code execution at that point till it's closed, at which point you can ask the object for the password. Alternatively, you could use a observer pattern of some kind, but the benefit of the dialog is it can stop the user from navigating to other parts of the UI until it's dealt with – MadProgrammer Sep 20 '17 at 05:06
  • [As a pratical example](https://stackoverflow.com/questions/46294138/how-i-supposed-to-make-program-to-stop-and-wait-for-something-java/46294466?noredirect=1#comment79551570_46294466) – MadProgrammer Sep 20 '17 at 05:06
  • I would first suggest, instead of making different frames, use a card layout. Set cardlayout on jframe and add 2 panels on it. On first panel add your Pay screen, on second panel add 'Match' button screen. Then switch from 1 screen to another. This will reduce your code and also complexity. – Aman Sep 20 '17 at 05:32
  • And you've also been given the same recommendations to use a modal JDialog with an example before you re-asked your question, advice that you ignored at the time. Do believe and learn from him as he is quite knowledgeable in this subject. – Hovercraft Full Of Eels Sep 26 '17 at 14:26

2 Answers2

0

You need to pass data using constructors

First create a constructor inside the fetchPasswordClass

String fetchedPassword = null;
public fetchPasswordClass(String password){
 
 //then pass the value to fetchedPassword variable
 fetchedPassword = password;
 //then initialize the components
 initComponents();

}

--------------------------------

Then inside the trigPayClass inside the button action
fetchPasswordClass obj = new fetchPasswordClass(password);
obj.setVisible(true);
user3808887
  • 319
  • 2
  • 9
  • I can not call/get 'password' in constructor itself. In 'Another screen', I have various other validations to do. I am doing these validations step by step through various buttons in this screen. I should get password through 'Match' button only. Hence I do not want to get Password through constructor. Please suggest – sai kiran Sep 20 '17 at 05:04
  • not clear your requirement. You can only pass value from one class to another class through constructor or via a static variable – user3808887 Sep 20 '17 at 05:15
  • my requirement: There will be 2 screens, i.e. pay and Another screen. When I click on button in pay screen, through a function call I should be able to populate Another screen and return a String value to Pay screen. On Another screen, there will be 3 buttons and one of them will Match button. On press of Match button, I should get value from Database and return it to function that I mentioned above. That String will be returned to Pay screen. – sai kiran Sep 21 '17 at 03:21
0

Let's say this is your main window

public class MainWindow extends JFrame {
   private AnotherWindow another_window;

    public MainWindow() {
        init();        
        another_window = new AnotherWindow(this);
    }

    private void init() {
        //some codes for JFrame
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            new MainWindow().setVisible(true);
        });
    }

   public void your_event(/*some parameters*/) {
       another_window.setVisible(true);
       another_window.validateInfo(/*some values for the parameter*/); 
   }

}

This is the AnotherWindow

public class AnotherWindow extends JFrame {

    private MainWindow main_window;   

    public AnotherWindow(MainWindow main_window) {
        this.main_window = main_window;
    }

    public boolean validateInfo(/**some parameters like string password, string username**/) {
        return result;
    }

}

The idea behind this is to let the "objects" know who called them. In this example, the MainWindow creates an instance of AnotherWindow. in the AnotherWindow class, we created a parameter for the object who will call it. We declared a MainWindow object in AnotherWindow class but not assigned a value to it because we don't know yet what specific instance of MainWindow will call the AnotherWindow.

Mr. Leeds
  • 154
  • 2
  • 11