Example usage for javax.swing JPasswordField getPassword

List of usage examples for javax.swing JPasswordField getPassword

Introduction

In this page you can find the example usage for javax.swing JPasswordField getPassword.

Prototype

@BeanProperty(bound = false)
public char[] getPassword() 

Source Link

Document

Returns the text contained in this TextComponent.

Usage

From source file:com.intel.stl.ui.common.view.ComponentFactory.java

public static JPasswordField createPasswordField(DocumentListener... docListeners) {
    final JPasswordField field = new JPasswordField();
    final Border oldBorder = field.getBorder();
    if (docListeners != null) {
        for (DocumentListener docListener : docListeners) {
            field.getDocument().addDocumentListener(docListener);
            field.getDocument().putProperty("owner", field);
        }/* www  .  j  a v  a2 s  . c o m*/
    }
    final InputVerifier verifier = new InputVerifier() {
        @Override
        public boolean verify(final JComponent input) {
            final JPasswordField field = (JPasswordField) input;
            char[] txt = field.getPassword();
            if (txt.length == 0) {
                // Run in EDT to avoid deadlock in case this gets called
                // from not swing thread
                Util.runInEDT(new Runnable() {
                    @Override
                    public void run() {
                        field.setToolTipText(UILabels.STL50084_CANT_BE_BLANK.getDescription());
                        input.setBackground(UIConstants.INTEL_LIGHT_RED);
                        input.setBorder(BorderFactory.createLineBorder(UIConstants.INTEL_RED, 2));
                        // show tooltip immediately
                        ToolTipManager.sharedInstance()
                                .mouseMoved(new MouseEvent(field, 0, 0, 0, 0, 0, 0, false));
                    }
                });
                return false;
            } else {
                Util.runInEDT(new Runnable() {
                    @Override
                    public void run() {
                        input.setBackground(UIConstants.INTEL_WHITE);
                        input.setBorder(oldBorder);
                    }
                });
                return true;
            }
        }

    };

    DocumentListener dynamicChecker = new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            verifier.verify(field);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            verifier.verify(field);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            verifier.verify(field);
        }

    };
    field.getDocument().addDocumentListener(dynamicChecker);

    // Add the input verifier
    field.setInputVerifier(verifier);

    return field;
}

From source file:edu.smc.mediacommons.panels.PasswordPanel.java

public PasswordPanel() {
    setLayout(null);//from w  ww . j  av a 2  s  .  co  m

    add(Utils.createLabel("Enter a Password to Test", 60, 30, 200, 20, null));

    final JButton test = Utils.createButton("Test", 260, 50, 100, 20, null);
    add(test);

    final JPasswordField fieldPassword = new JPasswordField(32);
    fieldPassword.setBounds(60, 50, 200, 20);
    add(fieldPassword);

    final PieDataset dataset = createSampleDataset(33, 33, 33);
    final JFreeChart chart = createChart(dataset);
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(300, 300));
    chartPanel.setBounds(45, 80, 340, 250);

    add(chartPanel);

    test.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String password = new String(fieldPassword.getPassword());

            if (password.isEmpty() || password == null) {
                JOptionPane.showMessageDialog(getParent(), "Warning! The input was blank!", "Invalid Input",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                int letterCount = 0, numberCount = 0, specialCount = 0, total = password.length();

                for (char c : password.toCharArray()) {
                    if (Character.isLetter(c)) {
                        letterCount++;
                    } else if (Character.isDigit(c)) {
                        numberCount++;
                    } else {
                        specialCount++;
                    }
                }

                long totalCombinations = 0;
                double percentLetters = 0;
                double percentNumbers = 0;
                double percentCharacters = 0;

                if (letterCount > 0) {
                    totalCombinations += (factorial(26) / factorial(26 - letterCount));
                    percentLetters = (letterCount + 0.0 / total);
                }

                if (numberCount > 0) {
                    totalCombinations += (factorial(10) / factorial(10 - numberCount));
                    percentNumbers = (numberCount + 0.0 / total);
                }

                if (specialCount > 0) {
                    totalCombinations += (factorial(40) / factorial(40 - specialCount));
                    percentCharacters = (specialCount + 0.0 / total);
                }

                PieDataset dataset = createSampleDataset(percentLetters, percentNumbers, percentCharacters);
                JFreeChart chart = createChart(dataset);
                chartPanel.setChart(chart);

                JOptionPane.showMessageDialog(getParent(),
                        "Total Combinations: " + totalCombinations + "\nAssuming Rate Limited, Single: "
                                + (totalCombinations / 1000) + " seconds" + "\n\nBreakdown:\nLetters: "
                                + percentLetters + "%\nNumbers: " + percentNumbers + "%\nCharacters: "
                                + percentCharacters + "%");
            }
        }
    });

    setVisible(true);
}

From source file:com.gs.obevo.util.inputreader.DialogInputReader.java

@Override
public String readPassword(String promptMessage) {
    final JPasswordField jpf = new JPasswordField();
    JOptionPane jop = new JOptionPane(jpf, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dialog = jop.createDialog(promptMessage);
    dialog.addComponentListener(new ComponentAdapter() {
        @Override/*from  www  .j  av a 2 s  . c om*/
        public void componentShown(ComponentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    jpf.requestFocusInWindow();
                }
            });
        }
    });
    dialog.setVisible(true);
    int result = (Integer) jop.getValue();
    dialog.dispose();
    String password = null;
    if (result == JOptionPane.OK_OPTION) {
        password = new String(jpf.getPassword());
    }
    if (StringUtils.isEmpty(password)) {
        return null;
    } else {
        return password;
    }
}

From source file:com.sun.jersey.client.apache.config.DefaultCredentialsProvider.java

public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
        throws CredentialsNotAvailableException {
    if (scheme == null) {
        return null;
    }//ww  w  .j a v  a 2 s.c  om

    try {
        JTextField userField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        int response;

        if (scheme instanceof NTLMScheme) {
            JTextField domainField = new JTextField();
            Object[] msg = { host + ":" + port + " requires Windows authentication", "Domain", domainField,
                    "User Name", userField, "Password", passwordField };
            response = JOptionPane.showConfirmDialog(null, msg, "Authenticate", JOptionPane.OK_CANCEL_OPTION);

            if ((response == JOptionPane.CANCEL_OPTION) || (response == JOptionPane.CLOSED_OPTION)) {
                throw new CredentialsNotAvailableException("User cancled windows authentication.");
            }

            return new NTCredentials(userField.getText(), new String(passwordField.getPassword()), host,
                    domainField.getText());

        } else if (scheme instanceof RFC2617Scheme) {
            Object[] msg = {
                    host + ":" + port + " requires authentication with the realm '" + scheme.getRealm() + "'",
                    "User Name", userField, "Password", passwordField };

            response = JOptionPane.showConfirmDialog(null, msg, "Authenticate", JOptionPane.OK_CANCEL_OPTION);

            if ((response == JOptionPane.CANCEL_OPTION) || (response == JOptionPane.CLOSED_OPTION)) {
                throw new CredentialsNotAvailableException("User cancled windows authentication.");
            }

            return new UsernamePasswordCredentials(userField.getText(),
                    new String(passwordField.getPassword()));

        } else {

            throw new CredentialsNotAvailableException(
                    "Unsupported authentication scheme: " + scheme.getSchemeName());

        }
    } catch (IOException ioe) {

        throw new CredentialsNotAvailableException(ioe.getMessage(), ioe);

    }
}

From source file:TextComponentTest.java

public TextComponentFrame() {
    setTitle("TextComponentTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    final JTextField textField = new JTextField();
    final JPasswordField passwordField = new JPasswordField();

    JPanel northPanel = new JPanel();
    northPanel.setLayout(new GridLayout(2, 2));
    northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
    northPanel.add(textField);/*from  w w  w .ja v a2  s  . com*/
    northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
    northPanel.add(passwordField);

    add(northPanel, BorderLayout.NORTH);

    final JTextArea textArea = new JTextArea(8, 40);
    JScrollPane scrollPane = new JScrollPane(textArea);

    add(scrollPane, BorderLayout.CENTER);

    // add button to append text into the text area

    JPanel southPanel = new JPanel();

    JButton insertButton = new JButton("Insert");
    southPanel.add(insertButton);
    insertButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            textArea.append("User name: " + textField.getText() + " Password: "
                    + new String(passwordField.getPassword()) + "\n");
        }
    });

    add(southPanel, BorderLayout.SOUTH);

    // add a text area with scroll bars

}

From source file:com.paniclauncher.data.Instance.java

public void launch() {
    final Account account = App.settings.getAccount();
    if (account == null) {
        String[] options = { App.settings.getLocalizedString("common.ok") };
        JOptionPane.showOptionDialog(App.settings.getParent(),
                App.settings.getLocalizedString("instance.noaccount"),
                App.settings.getLocalizedString("instance.noaccountselected"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        App.settings.setMinecraftLaunched(false);
    } else {//from   www. j  a  v a 2 s . co  m
        String username = account.getUsername();
        String password = account.getPassword();
        if (!account.isRemembered()) {
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            JLabel passwordLabel = new JLabel(
                    App.settings.getLocalizedString("instance.enterpassword", account.getMinecraftUsername()));
            JPasswordField passwordField = new JPasswordField();
            panel.add(passwordLabel, BorderLayout.NORTH);
            panel.add(passwordField, BorderLayout.CENTER);
            int ret = JOptionPane.showConfirmDialog(App.settings.getParent(), panel,
                    App.settings.getLocalizedString("instance.enterpasswordtitle"),
                    JOptionPane.OK_CANCEL_OPTION);
            if (ret == JOptionPane.OK_OPTION) {
                password = new String(passwordField.getPassword());
            } else {
                App.settings.setMinecraftLaunched(false);
                return;
            }
        }
        boolean loggedIn = false;
        String url = null;
        String sess = null;
        String auth = null;
        if (!App.settings.isInOfflineMode()) {
            if (isNewLaunchMethod()) {
                String result = Utils.newLogin(username, password);
                if (result == null) {
                    loggedIn = true;
                    sess = "token:0:0";
                } else {
                    JSONParser parser = new JSONParser();
                    try {
                        Object obj = parser.parse(result);
                        JSONObject jsonObject = (JSONObject) obj;
                        if (jsonObject.containsKey("accessToken")) {
                            String accessToken = (String) jsonObject.get("accessToken");
                            JSONObject profile = (JSONObject) jsonObject.get("selectedProfile");
                            String profileID = (String) profile.get("id");
                            sess = "token:" + accessToken + ":" + profileID;
                            loggedIn = true;
                        } else {
                            auth = (String) jsonObject.get("errorMessage");
                        }
                    } catch (ParseException e1) {
                        App.settings.getConsole().logStackTrace(e1);
                    }
                }
            } else {
                try {
                    url = "https://login.minecraft.net/?user=" + URLEncoder.encode(username, "UTF-8")
                            + "&password=" + URLEncoder.encode(password, "UTF-8") + "&version=999";
                } catch (UnsupportedEncodingException e1) {
                    App.settings.getConsole().logStackTrace(e1);
                }
                auth = Utils.urlToString(url);
                if (auth == null) {
                    loggedIn = true;
                    sess = "0";
                } else {
                    if (auth.contains(":")) {
                        String[] parts = auth.split(":");
                        if (parts.length == 5) {
                            loggedIn = true;
                            sess = parts[3];
                        }
                    }
                }
            }
        } else {
            loggedIn = true;
            sess = "token:0:0";
        }
        if (!loggedIn) {
            String[] options = { App.settings.getLocalizedString("common.ok") };
            JOptionPane
                    .showOptionDialog(App.settings.getParent(),
                            "<html><center>" + App.settings.getLocalizedString("instance.errorloggingin",
                                    "<br/><br/>" + auth) + "</center></html>",
                            App.settings.getLocalizedString("instance.errorloggingintitle"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
            App.settings.setMinecraftLaunched(false);
        } else {
            final String session = sess;
            Thread launcher = new Thread() {
                public void run() {
                    try {
                        long start = System.currentTimeMillis();
                        if (App.settings.getParent() != null) {
                            App.settings.getParent().setVisible(false);
                        }
                        Process process = null;
                        if (isNewLaunchMethod()) {
                            process = NewMCLauncher.launch(account, Instance.this, session);
                        } else {
                            process = MCLauncher.launch(account, Instance.this, session);
                        }
                        App.settings.showKillMinecraft(process);
                        InputStream is = process.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String line;
                        while ((line = br.readLine()) != null) {
                            App.settings.getConsole().logMinecraft(line);
                        }
                        App.settings.hideKillMinecraft();
                        if (App.settings.getParent() != null) {
                            App.settings.getParent().setVisible(true);
                        }
                        long end = System.currentTimeMillis();
                        if (App.settings.isInOfflineMode()) {
                            App.settings.checkOnlineStatus();
                        }
                        App.settings.setMinecraftLaunched(false);
                        if (!App.settings.isInOfflineMode()) {
                            if (App.settings.isUpdatedFiles()) {
                                App.settings.reloadLauncherData();
                            }
                        }
                    } catch (IOException e1) {
                        App.settings.getConsole().logStackTrace(e1);
                    }
                }
            };
            launcher.start();
        }
    }
}

From source file:com.eviware.soapui.DefaultSoapUICore.java

protected Settings initSettings(String fileName) {
    // TODO Why try to load settings from current directory before using root?
    // This caused a bug in Eclipse:
    // https://sourceforge.net/tracker/?func=detail&atid=737763&aid=2620284&group_id=136013
    File settingsFile = new File(fileName).exists() ? new File(fileName) : null;

    try {//from  w ww. j  a  va 2  s  .co  m
        if (settingsFile == null) {
            settingsFile = new File(new File(getRoot()), DEFAULT_SETTINGS_FILE);
            if (!settingsFile.exists()) {
                settingsFile = new File(new File(System.getProperty("user.home", ".")), DEFAULT_SETTINGS_FILE);
                lastSettingsLoad = 0;
            }
        } else {
            settingsFile = new File(fileName);
            if (!settingsFile.getAbsolutePath().equals(this.settingsFile))
                lastSettingsLoad = 0;
        }

        if (!settingsFile.exists()) {
            if (settingsDocument == null) {
                log.info("Creating new settings at [" + settingsFile.getAbsolutePath() + "]");
                settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
                setInitialImport(true);
            }

            lastSettingsLoad = System.currentTimeMillis();
        } else if (settingsFile.lastModified() > lastSettingsLoad) {
            settingsDocument = SoapuiSettingsDocumentConfig.Factory.parse(settingsFile);

            byte[] encryptedContent = settingsDocument.getSoapuiSettings().getEncryptedContent();
            if (encryptedContent != null) {
                char[] password = null;
                if (this.password == null) {
                    // swing element -!! uh!
                    JPasswordField passwordField = new JPasswordField();
                    JLabel qLabel = new JLabel("Password");
                    JOptionPane.showConfirmDialog(null, new Object[] { qLabel, passwordField },
                            "Global Settings", JOptionPane.OK_CANCEL_OPTION);
                    password = passwordField.getPassword();
                } else {
                    password = this.password.toCharArray();
                }

                byte[] data = OpenSSL.decrypt("des3", password, encryptedContent);
                try {
                    settingsDocument = SoapuiSettingsDocumentConfig.Factory.parse(new String(data, "UTF-8"));
                } catch (Exception e) {
                    log.warn("Wrong password.");
                    JOptionPane.showMessageDialog(null,
                            "Wrong password, creating backup settings file [ " + settingsFile.getAbsolutePath()
                                    + ".bak.xml. ]\nSwitch to default settings.",
                            "Error - Wrong Password", JOptionPane.ERROR_MESSAGE);
                    settingsDocument.save(new File(settingsFile.getAbsolutePath() + ".bak.xml"));
                    throw e;
                }
            }

            log.info("initialized soapui-settings from [" + settingsFile.getAbsolutePath() + "]");
            lastSettingsLoad = settingsFile.lastModified();

            if (settingsWatcher == null) {
                settingsWatcher = new SettingsWatcher();
                SoapUI.getSoapUITimer().scheduleAtFixedRate(settingsWatcher, 10000, 10000);
            }
        }
    } catch (Exception e) {
        log.warn("Failed to load settings from [" + e.getMessage() + "], creating new");
        settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
        lastSettingsLoad = 0;
    }

    if (settingsDocument.getSoapuiSettings() == null) {
        settingsDocument.addNewSoapuiSettings();
        settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());

        initDefaultSettings(settings);
    } else {
        settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());
    }

    this.settingsFile = settingsFile.getAbsolutePath();

    if (!settings.isSet(WsdlSettings.EXCLUDED_TYPES)) {
        StringList list = new StringList();
        list.add("schema@http://www.w3.org/2001/XMLSchema");
        settings.setString(WsdlSettings.EXCLUDED_TYPES, list.toXml());
    }

    if (!settings.isSet(WebRecordingSettings.EXCLUDED_HEADERS)) {
        StringList list = new StringList();
        list.add("Cookie");
        list.add("Set-Cookie");
        list.add("Referer");
        list.add("Keep-Alive");
        list.add("Connection");
        list.add("Proxy-Connection");
        list.add("Pragma");
        list.add("Cache-Control");
        list.add("Transfer-Encoding");
        list.add("Date");
        settings.setString(WebRecordingSettings.EXCLUDED_HEADERS, list.toXml());
    }

    if (settings.getString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1)
            .equals(HttpSettings.HTTP_VERSION_0_9)) {
        settings.setString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    }

    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, true);
    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, 500);
    setIfNotSet(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    setIfNotSet(HttpSettings.MAX_TOTAL_CONNECTIONS, 2000);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(UISettings.AUTO_SAVE_PROJECTS_ON_EXIT, true);
    setIfNotSet(UISettings.SHOW_DESCRIPTIONS, true);
    setIfNotSet(WsdlSettings.XML_GENERATION_ALWAYS_INCLUDE_OPTIONAL_ELEMENTS, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(WsdlSettings.CACHE_WSDLS, true);
    setIfNotSet(WsdlSettings.PRETTY_PRINT_RESPONSE_MESSAGES, true);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(UISettings.AUTO_SAVE_INTERVAL, "0");
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(WsaSettings.SOAP_ACTION_OVERRIDES_WSA_ACTION, false);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.OVERRIDE_EXISTING_HEADERS, false);
    setIfNotSet(WsaSettings.ENABLE_FOR_OPTIONAL, false);
    setIfNotSet(VersionUpdateSettings.AUTO_CHECK_VERSION_UPDATE, true);

    boolean setWsiDir = false;
    String wsiLocationString = settings.getString(WSISettings.WSI_LOCATION, null);
    if (StringUtils.isNullOrEmpty(wsiLocationString)) {
        setWsiDir = true;
    } else {
        File wsiFile = new File(wsiLocationString);
        if (!wsiFile.exists()) {
            setWsiDir = true;
        }
    }
    if (setWsiDir) {
        String wsiDir = System.getProperty("wsi.dir", new File(".").getAbsolutePath());
        settings.setString(WSISettings.WSI_LOCATION, wsiDir);
    }
    HttpClientSupport.addSSLListener(settings);

    return settings;
}

From source file:frames.consulta.java

private void btneliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btneliminarActionPerformed
    int filase = tblconsulta.getSelectedRow();

    try {/*from  ww w. j  a  v a 2 s  .c om*/
        String cedula, nombre, ape, edad, direccion;
        if (filase == -1) {
            JOptionPane.showMessageDialog(null, "Debe Seleccionar un Paciente", "Advertencia",
                    JOptionPane.WARNING_MESSAGE);
        } else {

            int valor = JOptionPane.showConfirmDialog(this, "Esta Seguro eliminar el paciente?",
                    "Advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (valor == JOptionPane.YES_NO_OPTION) {
                JPasswordField pf = new JPasswordField();
                int okCxl = JOptionPane.showConfirmDialog(null, pf, "Enter Password",
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                if (okCxl == JOptionPane.OK_OPTION) {
                    String password = new String(pf.getPassword());
                    String cap = "", cap1 = "";
                    int id;
                    String encriptado = DigestUtils.md5Hex(password);

                    String sql = "";

                    sql = "SELECT * FROM administrador WHERE clave='" + encriptado + "'";

                    try {
                        Statement st = cn.createStatement();
                        ResultSet rs = st.executeQuery(sql);

                        while (rs.next()) {
                            id = rs.getInt("id_usuario");
                            cap = rs.getString("usuario");
                            cap1 = rs.getString("clave");
                        }

                        if (cap1.equals(encriptado)) {

                            modelo = (DefaultTableModel) tblconsulta.getModel();
                            cedula = tblconsulta.getValueAt(filase, 0).toString();
                            nombre = tblconsulta.getValueAt(filase, 1).toString();
                            ape = tblconsulta.getValueAt(filase, 2).toString();
                            edad = tblconsulta.getValueAt(filase, 3).toString();
                            direccion = tblconsulta.getValueAt(filase, 4).toString();

                            Eliminar(cedula);

                        } else {
                            JOptionPane.showMessageDialog(null, "Clave Invalida", "Advertencia",
                                    JOptionPane.WARNING_MESSAGE);

                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(null, ex);
                        ;
                    }
                    //System.err.println("You entered: " + password);
                }
                //System.exit(0);
            }
        }
    } catch (Exception e) {
        //registro.action = "Ver";
    }
}

From source file:edu.ku.brc.af.ui.db.DatabaseLoginPanel.java

/**
 * @return a username/password pair if valid or null if canceled
 * @throws SQLException/*from   w  w w.ja v a  2  s .  c  o m*/
 */
public static Pair<String, String> getITUsernamePwd() {
    JTextField userNameTF = UIHelper.createTextField(15);
    JPasswordField passwordTF = UIHelper.createPasswordField();
    JLabel statusLbl = UIHelper.createLabel("");

    JPanel loginPanel = createLoginPanel("IT_Username", userNameTF, "IT_Password", passwordTF, statusLbl,
            "MySQLFull");

    while (true) {
        CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(),
                UIRegistry.getResourceString("IT_LOGIN"), true, loginPanel);
        dlg.setVisible(true);
        if (!dlg.isCancelled()) {
            String uName = userNameTF.getText();
            String pwd = new String(passwordTF.getPassword());

            DBConnection dbc = DBConnection.getInstance();
            DBConnection dbConn = DBConnection.createInstance(dbc.getDriver(), dbc.getDialect(),
                    dbc.getDatabaseName(), dbc.getConnectionStr(), uName, pwd);
            if (dbConn != null) {
                DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
                dbMgr.close();

                if (dbMgr.connect(uName, pwd, dbc.getServerName(), dbc.getDatabaseName())) {
                    dbMgr.close();
                    return new Pair<String, String>(uName, pwd);
                }
                dbMgr.close();
                statusLbl.setText("<HTML><font color=\"red\">" + UIRegistry.getResourceString("IT_LOGIN_ERROR")
                        + "</font></HTML>");
            }
        } else {
            return null;
        }
    }
}

From source file:com._17od.upm.gui.DatabaseActions.java

/**
 * Prompt the user to enter a password/*  w w w  .  j  a  va  2 s  .  co  m*/
 * @return The password entered by the user or null of this hit escape/cancel
 */
private char[] askUserForPassword(String message) {
    char[] password = null;

    final JPasswordField masterPassword = new JPasswordField("");
    JOptionPane pane = new JOptionPane(new Object[] { message, masterPassword }, JOptionPane.QUESTION_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION);
    JDialog dialog = pane.createDialog(mainWindow, Translator.translate("masterPassword"));
    dialog.addWindowFocusListener(new WindowAdapter() {
        public void windowGainedFocus(WindowEvent e) {
            masterPassword.requestFocusInWindow();
        }
    });
    dialog.show();

    if (pane.getValue() != null && pane.getValue().equals(new Integer(JOptionPane.OK_OPTION))) {
        password = masterPassword.getPassword();
    }

    return password;
}