访问JAVA中的另一个类变量

时间:2013-12-23 20:59:05

标签: java variables

我的应用程序下面有Loginscreen; (我使用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                   
}

我使用此loginscreen来识别数据库中的用户。我有另一个SQLSP类用于在DB中执行存储过程。

如果用户使用真实登录详细信息成功登录系统,则会在屏幕上显示另一个java框架。当用户与此屏幕交互并从SQLSP类调用某些sqlsp时,我必须使用uname&amp; amp;登录到db。 loginscreen.java中的密码

但是uname和密码存储在

privatevoidBağlan_ButonActionPerformed(java.awt.event.ActionEvent evt)

下的

public class loginscreen扩展了javax.swing.JFrame

如何从另一个类访问用户和pwd变量?

我试试

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

但没有帮助。我怎样才能访问它们?

2 个答案:

答案 0 :(得分:4)

user是您班级方法中的局部变量。在声明它们的方法之外的任何地方都无法访问局部变量。

你真正想做的是在类中声明一个类变量:

private String username;

然后为此变量提供公共getter:

public String getUsername()
{
    return username;
}

然后在适当的地方在课堂内设置username。您班外的代码可以使用logindetails.getUsername()来访问存储的用户名。

答案 1 :(得分:2)

您可以使用多种可能性......

你可以

使用某种getter从登录类返回用户。的。您只需要以某种方式存储该值,然后将其传递给程序的其他部分

一般来说,我倾向于选择这个选项,但这可能意味着你最终将几十个参数传递给并不真正需要它们的类,因为它们有一个需要它的类或子类......

你可以

使用单例存储活动用户,因此当用户首次登录时,您将设置单例的值,以便程序的其他部分可以在需要时从单例中获取它。

如果您打算仅允许单个用户访问单个数据库,那么这很好。如果您需要支持多个数据库或用户,第一个选项将成为您唯一的选择