简体   繁体   中英

Access another class variable in JAVA

I have below Loginscreen for my application; (I use netbeans gui designer)

public class loginscreen extends javax.swing.JFrame {

    /**
     * Creates new form loginscreen
     */
    public loginscreen() {
        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() {

        Uname_Textfield = new javax.swing.JTextField();
        Password_PasswordField = new javax.swing.JPasswordField();
        Bağlan_Buton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        Uname_Textfield.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Uname_TextfieldActionPerformed(evt);
            }
        });

        Bağlan_Buton.setText("Bağlan");
        Bağlan_Buton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Bağlan_ButonActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(Bağlan_Buton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(Uname_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Password_PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Bağlan_Buton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

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

    private void Bağlan_ButonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
       String user=Uname_Textfield.getText();
       String pwd= new String (Password_PasswordField.getPassword());
    try {  
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://192.168.131.10;" + "databaseName=ExampleDB;" + "user=" + user + ";" + "password=" + pwd + ";"; 
        Connection con = DriverManager.getConnection(connectionUrl);
        new ProgramPenceresi().setVisible(true);
        dispose();
        }
    catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Kullanıcı Adı veya Şifre Yanlış!");   
        } 
    catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: "+ cE.toString());
        }
    }                                            

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton Bağlan_Buton;
    private javax.swing.JPasswordField Password_PasswordField;
    private javax.swing.JTextField Uname_Textfield;
    // End of variables declaration                   
}

I use this loginscreen for identify users in DB. I have another SQLSP class for executing for stored procedures in DB.

If users succesfully login to system with true login details another java frame appear on screen. When users interract with this screen and call some sqlsp from SQLSP class i must login to db with using uname & password in loginscreen.java

But uname and password stored in

private void Bağlan_ButonActionPerformed(java.awt.event.ActionEvent evt)

under

public class loginscreen extends javax.swing.JFrame

How can access user and pwd variable from another class?

I try

loginscreen logindetails = new loginscreen();
String username = logindetails.user;

But no help. How can i access them ?

user is a local variable inside a method of your class. Local variables can't be accessed anywhere outside the method they're declared in.

What you really want to do is to declare a class variable inside the class:

private String username;

Then provide a public getter for this variable:

public String getUsername()
{
    return username;
}

Then set username inside your class in the appropriate place. Code outside your class can use logindetails.getUsername() to access the stored username.

There are any number of possibilities you might use...

You Could

Return the user from the login class, using a getter of some sort. The. You would simply need to store the value in some way that it could then be passed to other parts of the program

Generally I tend to prefer this option, but it can mean that you end up passing dozens of parameters to classes that don't really need them because they have a class or child class that needs it...

You Could

Use a singleton to store the active user, so when the user is first logged in, you would set the value of the singleton so that other parts of the program could get it from the singleton when they needed it.

This is good if you intend to only allow access to a single database for a single user. If you need to support multiple databases or users, the first option becomes your only choice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM