Как сохранить учетные данные, введенные в диалоговом окне входа в систему, и получить к нему доступ в другом классе? - PullRequest
0 голосов
/ 16 мая 2019

У меня есть два класса и один основной. В одном классе, LoginDialog, у меня есть метод actionPerformed (), который запрашивает диалоговое окно входа в систему, в которое пользователь вводит свои учетные данные. Метод также включает параметр ActionEvent. Как сохранить эти учетные данные, чтобы я мог позвонить / получить доступ к нему в моем другом классе, Transfer. Я включил метод getUser () в класс LoginDialog, который вызывает actionPerformed () и пытается напечатать пользователя и вызвал метод getUser () при передаче другого класса, но я продолжаю получать исключение nullpointerexception.

Main:

public static void main(String[] args) {
    Transfer transfer = new Transfer();

    JFrame parentFrame = new JFrame("Transfer Login");
    parentFrame.setBounds(400, 400, 400, 400);

    // Create and set up the window.
    JDialog loginDialog = new JDialog(parentFrame, "Transfer Login", Dialog.ModalityType.DOCUMENT_MODAL);

    loginDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // Create and set up the content pane.
    final LoginDialog newContentPane = new LoginDialog(loginDialog, bltFrame);
    Container c1 = newContentPane.getContentPane();
    loginDialog.setContentPane(c1);

    // Make sure the focus goes to the right component
    // whenever the frame is initially given the focus.
    newContentPane.addWindowListener(new WindowAdapter() {
        public void windowActivated(WindowEvent e) {
            newContentPane.resetFocus();
        }

        public void windowClosed(WindowEvent e) {
            System.out.println("jdialog window closed");
        }

    });
    loginDialog.pack();
    // This will hang until the dialog is closed
    loginDialog.setVisible(true);
    newContentPane.getUser(e);
    transfer.print();
}

LoginDialog:

public class LoginDialog extends JDialog implements ActionListener {

    public String user;
    public char [] pw;

    private String OK = "ok";
    private String HELP = "help";

    private JFrame controllingFrame; // needed for dialogs
    private JTextField userField;
    private JPasswordField passwordField;
    private TransferService transferService;
    BaselineTransferFrame btf;

    public LoginDialog(JDialog loginDialog, BaselineTransferFrame bltFrame) {
        // Use the default FlowLayout.
        controllingFrame = (JFrame) loginDialog.getParent();
        transferService = bltFrame.getTransferService();
        btf = bltFrame;

        // Create everything.
        userField = new JTextField(12);
        passwordField = new JPasswordField(20);
        passwordField.setActionCommand(OK);
        passwordField.addActionListener(this);

        JLabel uLabel = new JLabel("Enter your Dimensions User ID: ");
        JLabel pLabel = new JLabel("Enter password: ");
        uLabel.setLabelFor(userField);
        pLabel.setLabelFor(passwordField);

        // Lay out everything.
        JPanel textPane = new JPanel(new GridLayout(3, 1));
        textPane.add(uLabel);
        textPane.add(userField);
        textPane.add(pLabel);
        textPane.add(passwordField);
        textPane.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder()));

        JComponent buttonPane = createButtonPanel(textPane);

        add(textPane);
        add(buttonPane);

    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        if (OK.equals(cmd)) { // Process the password.
            user = userField.getText();
            pw = passwordField.getPassword();
            HashMap<String, String> connectParms = transferService.getConnectionParms("a");
            DimensionsSession dmSession = null;
            try {
                dmSession = transferService.connectToDimensions(connectParms.get("server"), connectParms.get("connection"), connectParms.get("database"), user, String.valueOf(pw));
                System.out.println("Here");
            } catch (BaselineTransferException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (dmSession != null) {
                JOptionPane.showMessageDialog(controllingFrame, "Success! You typed the right password.");
                dmSession.close();
                controllingFrame.dispose();
            } else {
                JOptionPane.showMessageDialog(controllingFrame, "Invalid password. Try again.", "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }

            // Zero out the possible password, for security.
            Arrays.fill(pw, '0');

            passwordField.selectAll();
            resetFocus();
        } else { // The user has asked for help.
            JOptionPane.showMessageDialog(controllingFrame,
                    "You can get the password by searching this example's\n"
                            + "source code for the string \"correctPassword\".\n"
                            + "Or look at the section How to Use Password Fields in\n"
                            + "the components section of The Java Tutorial.");
        }
    }

    public void getUser(ActionEvent e){
        actionPerformed(e);
        System.out.println(user);
    }

Перевод:

public void print(){
    ActionEvent e = null;
    LoginDialog user1 = new LoginDialog(loginDialog, bltFrame);
    user1.getUser(e);
}

Выход:

Caused by: java.lang.NullPointerException
at com.northgrum.ssee.gui.LoginDialog.getUser(LoginDialog(The line with String cmd = e.getActionCommand(); in the method actionPerformed()))

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
... 13 more
...