繁体   English   中英

在JAVA中访问另一个类变量

[英]Access another class variable in JAVA

我的应用程序位于登录屏幕下方; (我使用netbeans gui设计器)

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                   
}

我使用此登录屏幕来标识数据库中的用户。 我还有另一个SQLSP类,用于执行数据库中的存储过程。

如果用户使用真正的登录详细信息成功登录到系统,则屏幕上将出现另一个Java框架。 当用户干预此屏幕并从SQLSP类调用某些sqlsp时,我必须使用loginscreen.java中的uname和password登录到db。

但是uname和密码存储在

私有无效Bağlan_ButonActionPerformed(java.awt.event.ActionEvent evt)

公共类loginscreen扩展了javax.swing.JFrame

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

我尝试

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

但是没有帮助。 我如何访问它们?

user是类方法内的局部变量。 局部变量不能在声明它们的方法之外的任何地方访问。

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

private String username;

然后为该变量提供一个公共获取器:

public String getUsername()
{
    return username;
}

然后在班级中的适当位置设置username 类外的代码可以使用logindetails.getUsername()来访问存储的用户名。

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

你可以

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

通常,我倾向于使用此选项,但这可能意味着您最终将数十个参数传递给实际上并不需要它们的类,因为它们具有需要该参数的类或子类...

你可以

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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