Example usage for javax.swing JPasswordField JPasswordField

List of usage examples for javax.swing JPasswordField JPasswordField

Introduction

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

Prototype

public JPasswordField(int columns) 

Source Link

Document

Constructs a new empty JPasswordField with the specified number of columns.

Usage

From source file:org.rdv.ui.LoginDialog.java

public LoginDialog(JFrame owner) {
    super(owner, true);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    setTitle("Login to NEES");

    JPanel container = new JPanel();
    setContentPane(container);//  w w w.  j  a  v  a2s . com

    InputMap inputMap = container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = container.getActionMap();

    container.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.weighty = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.ipadx = 0;
    c.ipady = 0;

    headerLabel = new JLabel("Please specify your NEES account information.");
    headerLabel.setBackground(Color.white);
    headerLabel.setOpaque(true);
    headerLabel.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray),
                    BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new Insets(0, 0, 0, 0);
    container.add(headerLabel, c);

    errorLabel = new JLabel();
    errorLabel.setVisible(false);
    errorLabel.setForeground(Color.RED);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 1;
    c.insets = new Insets(10, 10, 0, 10);
    container.add(errorLabel, c);

    c.gridwidth = 1;

    userNameLabel = new JLabel("Username:");
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 2;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new Insets(10, 10, 10, 5);
    container.add(userNameLabel, c);

    userNameTextField = new JTextField("", 25);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    c.gridx = 1;
    c.gridy = 2;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.insets = new Insets(10, 0, 10, 10);
    container.add(userNameTextField, c);

    userPasswordLabel = new JLabel("Password:");
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 3;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new Insets(0, 10, 10, 5);
    container.add(userPasswordLabel, c);

    userPasswordField = new JPasswordField(16);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    c.gridx = 1;
    c.gridy = 3;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.insets = new Insets(0, 0, 10, 10);
    container.add(userPasswordField, c);

    JPanel buttonPanel = new JPanel();

    Action loginAction = new AbstractAction() {
        /** serialization version identifier */
        private static final long serialVersionUID = -5591044023056646223L;

        public void actionPerformed(ActionEvent e) {
            login();
        }
    };
    loginAction.putValue(Action.NAME, "Login");
    inputMap.put(KeyStroke.getKeyStroke("ENTER"), "login");
    actionMap.put("login", loginAction);
    loginButton = new JButton(loginAction);
    buttonPanel.add(loginButton);

    Action cancelAction = new AbstractAction() {
        /** serialization version identifier */
        private static final long serialVersionUID = 6237115705468556255L;

        public void actionPerformed(ActionEvent e) {
            cancel();
        }
    };
    cancelAction.putValue(Action.NAME, "Cancel");
    inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "cancel");
    actionMap.put("cancel", cancelAction);
    cancelButton = new JButton(cancelAction);
    buttonPanel.add(cancelButton);

    c.fill = GridBagConstraints.NONE;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 4;
    c.gridwidth = 2;
    c.anchor = GridBagConstraints.LINE_END;
    c.insets = new Insets(0, 10, 10, 5);
    container.add(buttonPanel, c);

    pack();
    setLocationByPlatform(true);
    setVisible(true);
}

From source file:org.thelq.stackexchange.dbimport.gui.GUI.java

public GUI(Controller passedController) {
    //Initialize logger
    logAppender = new GUILogAppender(this);

    //Set our Look&Feel
    try {//  w w  w  . j  a  va2s. c o m
        if (SystemUtils.IS_OS_WINDOWS)
            UIManager.setLookAndFeel(new WindowsLookAndFeel());
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.warn("Defaulting to Swing L&F due to exception", e);
    }

    this.controller = passedController;
    frame = new JFrame();
    frame.setTitle("Unified StackExchange Data Dump Importer v" + Controller.VERSION);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    //Setup menu
    JMenuBar menuBar = new JMenuBar();
    menuAdd = new JMenuItem("Add Folders/Archives");
    menuAdd.setMnemonic(KeyEvent.VK_F);
    menuBar.add(menuAdd);
    frame.setJMenuBar(menuBar);

    //Primary panel
    FormLayout primaryLayout = new FormLayout("5dlu, pref:grow, 5dlu, 5dlu, pref",
            "pref, top:pref, pref, fill:140dlu:grow, pref, fill:80dlu");
    PanelBuilder primaryBuilder = new PanelBuilder(primaryLayout)
            .border(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    //DB Config panel
    primaryBuilder.addSeparator("Database Configuration", CC.xyw(1, 1, 2));
    FormLayout configLayout = new FormLayout("pref, 3dlu, pref:grow, 6dlu, pref",
            "pref, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow");
    configLayout.setHonorsVisibility(true);
    final PanelBuilder configBuilder = new PanelBuilder(configLayout);
    configBuilder.addLabel("Server", CC.xy(1, 2), dbType = new JComboBox<DatabaseOption>(), CC.xy(3, 2));
    configBuilder.add(dbAdvanced = new JCheckBox("Show advanced options"), CC.xy(5, 2));
    configBuilder.addLabel("JDBC Connection", CC.xy(1, 4), jdbcString = new JTextField(15), CC.xyw(3, 4, 3));
    configBuilder.addLabel("Username", CC.xy(1, 6), username = new JTextField(10), CC.xy(3, 6));
    configBuilder.addLabel("Password", CC.xy(1, 8), password = new JPasswordField(10), CC.xy(3, 8));
    configBuilder.add(importButton = new JButton("Import"), CC.xywh(5, 6, 1, 3));
    //Add hidden
    JLabel dialectLabel = new JLabel("Dialect");
    dialectLabel.setVisible(false);
    configBuilder.add(dialectLabel, CC.xy(1, 10), dialect = new JTextField(10), CC.xyw(3, 10, 3));
    dialect.setVisible(false);
    JLabel driverLabel = new JLabel("Driver");
    driverLabel.setVisible(false);
    configBuilder.add(driverLabel, CC.xy(1, 12), driver = new JTextField(10) {
        @Override
        public void setText(String text) {
            if (StringUtils.isBlank(text))
                log.debug("Text is blank", new RuntimeException("Text " + text + " is blank"));
            super.setText(text);
        }
    }, CC.xyw(3, 12, 3));
    driver.setVisible(false);
    primaryBuilder.add(configBuilder.getPanel(), CC.xy(2, 2));

    //Options
    primaryBuilder.addSeparator("Options", CC.xyw(4, 1, 2));
    FormLayout optionsLayout = new FormLayout("pref, 3dlu, pref:grow", "");
    DefaultFormBuilder optionsBuilder = new DefaultFormBuilder(optionsLayout);
    optionsBuilder.append(disableCreateTables = new JCheckBox("Disable Creating Tables"), 3);
    optionsBuilder.append("Global Table Prefix", globalTablePrefix = new JTextField(7));
    optionsBuilder.append("Threads", threads = new JSpinner());
    //Save a core for the database
    int numThreads = Runtime.getRuntime().availableProcessors();
    numThreads = (numThreads != 1) ? numThreads - 1 : numThreads;
    threads.setModel(new SpinnerNumberModel(numThreads, 1, 100, 1));
    optionsBuilder.append("Batch Size", batchSize = new JSpinner());
    batchSize.setModel(new SpinnerNumberModel(500, 1, 500000, 1));
    primaryBuilder.add(optionsBuilder.getPanel(), CC.xy(5, 2));

    //Locations
    primaryBuilder.addSeparator("Dump Locations", CC.xyw(1, 3, 5));
    FormLayout locationsLayout = new FormLayout("pref, 15dlu, pref, 5dlu, pref, 5dlu, pref:grow, 2dlu, pref",
            "");
    locationsBuilder = new DefaultFormBuilder(locationsLayout, new ScrollablePanel()).background(Color.WHITE)
            .lineGapSize(Sizes.ZERO);
    locationsPane = new JScrollPane(locationsBuilder.getPanel());
    locationsPane.getViewport().setBackground(Color.white);
    locationsPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    locationsPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    primaryBuilder.add(locationsPane, CC.xyw(2, 4, 4));

    //Logger
    primaryBuilder.addSeparator("Log", CC.xyw(1, 5, 5));
    loggerText = new JTextPane();
    loggerText.setEditable(false);
    JPanel loggerTextPanel = new JPanel(new BorderLayout());
    loggerTextPanel.add(loggerText);
    JScrollPane loggerPane = new JScrollPane(loggerTextPanel);
    loggerPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    loggerPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    JPanel loggerPanePanel = new JPanel(new BorderLayout());
    loggerPanePanel.add(loggerPane);
    primaryBuilder.add(loggerPanePanel, CC.xyw(2, 6, 4));

    menuAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO: Allow 7z files but handle corner cases
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.setMultiSelectionEnabled(true);
            fc.setDialogTitle("Select Folders/Archives");
            fc.addChoosableFileFilter(new FileNameExtensionFilter("Archives", "7z", "zip"));
            fc.addChoosableFileFilter(new FileFilter() {
                @Getter
                protected String description = "Folders";

                @Override
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });

            if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)
                return;

            //Add files and folders in a seperate thread while updating gui in EDT
            importButton.setEnabled(false);
            for (File curFile : fc.getSelectedFiles()) {
                DumpContainer dumpContainer = null;
                try {
                    if (curFile.isDirectory())
                        dumpContainer = new FolderDumpContainer(curFile);
                    else
                        dumpContainer = new ArchiveDumpContainer(controller, curFile);
                    controller.addDumpContainer(dumpContainer);
                } catch (Exception ex) {
                    String type = (dumpContainer != null) ? dumpContainer.getType() : "";
                    LoggerFactory.getLogger(getClass()).error("Cannot open " + type, ex);
                    String location = (dumpContainer != null) ? Utils.getLongLocation(dumpContainer) : "";
                    showErrorDialog(ex, "Cannot open " + location, curFile.getAbsolutePath());
                    continue;
                }
            }
            updateLocations();
            importButton.setEnabled(true);
        }
    });

    //Add options (Could be in a map, but this is cleaner)
    dbType.addItem(new DatabaseOption().name("MySQL 5.5.3+")
            .jdbcString("jdbc:mysql://127.0.0.1:3306/stackexchange?rewriteBatchedStatements=true")
            .dialect("org.hibernate.dialect.MySQL5Dialect").driver("com.mysql.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.1")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL81Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.2+")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL82Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServerDialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2005+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2005Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2008+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2008Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("H2").jdbcString("jdbc:h2:stackexchange")
            .dialect("org.hibernate.dialect.H2Dialect").driver("org.h2.Driver"));
    dbType.setSelectedItem(null);
    dbType.addItemListener(new ItemListener() {
        boolean shownMysqlWarning = false;

        public void itemStateChanged(ItemEvent e) {
            //Don't run this twice for a single select
            if (e.getStateChange() == ItemEvent.DESELECTED)
                return;

            DatabaseOption selectedOption = (DatabaseOption) dbType.getSelectedItem();
            if (selectedOption.name().startsWith("MySQL") && !shownMysqlWarning) {
                //Hide popup so you don't have to click twice on the dialog 
                dbType.setPopupVisible(false);
                JOptionPane.showMessageDialog(frame,
                        "Warning: Your server must be configured with character_set_server=utf8mb4"
                                + "\nOtherwise, data dumps that contain 4 byte UTF-8 characters will fail",
                        "MySQL Warning", JOptionPane.WARNING_MESSAGE);
                shownMysqlWarning = true;
            }

            setDbOption(selectedOption);
        }
    });

    //Show and hide advanced options with checkbox
    dbAdvanced.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean selected = ((JCheckBox) e.getSource()).isSelected();
            driver.setVisible(selected);
            ((JLabel) driver.getClientProperty("labeledBy")).setVisible(selected);
            dialect.setVisible(selected);
            ((JLabel) dialect.getClientProperty("labeledBy")).setVisible(selected);
        }
    });

    importButton.addActionListener(new ActionListener() {
        protected void showImportError(String error) {
            JOptionPane.showMessageDialog(frame, error, "Configuration Error", JOptionPane.ERROR_MESSAGE);
        }

        protected void showInputErrorDatabase(String error) {
            if (dbType.getSelectedItem() == null)
                showImportError("No dbType specified, " + StringUtils.uncapitalize(error));
            else
                showImportError(error);
        }

        public void actionPerformed(ActionEvent e) {
            boolean validationPassed = false;
            if (controller.getDumpContainers().isEmpty())
                showImportError("Please add dump folders/archives");
            else if (StringUtils.isBlank(jdbcString.getText()))
                showInputErrorDatabase("Must specify JDBC String");
            else if (StringUtils.isBlank(driver.getText()))
                showInputErrorDatabase("Must specify driver");
            else if (StringUtils.isBlank(dialect.getText()))
                showInputErrorDatabase("Must specify hibernate dialect");
            else
                validationPassed = true;

            if (!validationPassed)
                return;

            //Disable all GUI components so they can't change anything during processing
            setGuiEnabled(false);

            //Run in new thread
            controller.getGeneralThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        start();
                    } catch (final Exception e) {
                        //Show an error message box
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                LoggerFactory.getLogger(getClass()).error("Cannot import", e);
                                showErrorDialog(e, "Cannot import", null);
                            }
                        });
                    }
                    //Renable GUI
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            setGuiEnabled(true);
                        }
                    });
                }
            });
        }
    });

    //Done, init logger
    logAppender.init();
    log.info("Finished creating GUI");

    //Display
    frame.setContentPane(primaryBuilder.getPanel());
    frame.pack();
    frame.setMinimumSize(frame.getSize());

    frame.setVisible(true);
}

From source file:org.tinymediamanager.ui.panels.MediaScraperConfigurationPanel.java

private JPanel createConfigPanel() {
    JPanel panel = new JPanel();
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0 };
    gridBagLayout.rowHeights = new int[] { 0 };
    gridBagLayout.columnWeights = new double[] { Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { Double.MIN_VALUE };
    panel.setLayout(gridBagLayout);/*from  w  ww  .  jav a2s.c  om*/

    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridy = 0;

    // build up the panel for being displayed in the popup
    MediaProviderConfig config = mediaProvider.getProviderInfo().getConfig();
    for (Entry<String, MediaProviderConfigObject> entry : config.getConfigObjects().entrySet()) {
        if (!entry.getValue().isVisible()) {
            continue;
        }

        constraints.anchor = GridBagConstraints.LINE_START;
        constraints.ipadx = 20;

        // label
        JLabel label = new JLabel(entry.getValue().getKeyDescription());
        constraints.gridx = 0;
        panel.add(label, constraints);

        JComponent comp;
        switch (entry.getValue().getType()) {
        case BOOL:
            // display as checkbox
            JCheckBox checkbox = new JCheckBox();
            checkbox.setSelected(entry.getValue().getValueAsBool());
            checkbox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dirty = true;
                }
            });
            comp = checkbox;
            break;

        case SELECT:
        case SELECT_INDEX:
            // display as combobox
            JComboBox<String> combobox = new JComboBox<>(
                    entry.getValue().getPossibleValues().toArray(new String[0]));
            combobox.setSelectedItem(entry.getValue().getValueAsString());
            combobox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dirty = true;
                }
            });
            comp = combobox;
            break;

        default:
            // display as text
            JTextField tf;
            if (entry.getValue().isEncrypt()) {
                tf = new JPasswordField(config.getValue(entry.getKey()));
            } else {
                tf = new JTextField(config.getValue(entry.getKey()));
            }

            tf.setPreferredSize(new Dimension(100, 24));
            tf.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void removeUpdate(DocumentEvent e) {
                    dirty = true;
                }

                @Override
                public void insertUpdate(DocumentEvent e) {
                    dirty = true;
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    dirty = true;
                }
            });
            comp = tf;
            break;
        }

        comp.putClientProperty(entry.getKey(), entry.getKey());
        constraints.ipadx = 0;
        constraints.gridx = 1;
        panel.add(comp, constraints);

        // add a hint if a long text has been found
        try {
            String desc = BUNDLE.getString(
                    "scraper." + mediaProvider.getProviderInfo().getId() + "." + entry.getKey() + ".desc"); //$NON-NLS-1$
            if (StringUtils.isNotBlank(desc)) {
                JLabel lblHint = new JLabel(IconManager.HINT);
                lblHint.setToolTipText(desc);
                constraints.gridx = 2;
                panel.add(lblHint, constraints);
            }
        } catch (Exception ignored) {
        }
        constraints.gridy++;
    }
    return panel;
}

From source file:pl.otros.vfs.browser.auth.UserPassUserAuthenticator.java

@Override
protected JPanel getOptionsPanel() {

    Collection<UserAuthenticationDataWrapper> userAuthenticationDatas = getAuthStore()
            .getUserAuthenticationDatas(getVfsUriParser().getProtocol().getName(),
                    getVfsUriParser().getHostname());
    String[] names = new String[userAuthenticationDatas.size()];
    int i = 0;//from  w w w  .j a v a2s .  c o m
    for (UserAuthenticationData userAuthenticationData : userAuthenticationDatas) {
        names[i] = new String(userAuthenticationData.getData(UserAuthenticationData.USERNAME));
        i++;
    }

    JPanel panel = new JPanel(new MigLayout());
    String header = Messages.getMessage("authenticator.enterCredentialsForUrl", getUrl());
    panel.add(new JLabel(header), "growx,span");
    panel.add(new JLabel(Messages.getMessage("authenticator.username")));
    nameTf = new JXComboBox(names);
    nameTf.setEditable(true);
    nameTf.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            userSelected(nameTf.getSelectedItem().toString());
        }
    });

    AutoCompleteDecorator.decorate(nameTf);
    nameTf.addAncestorListener(new AncestorListener() {

        @Override
        public void ancestorRemoved(AncestorEvent event) {

        }

        @Override
        public void ancestorMoved(AncestorEvent event) {

        }

        @Override
        public void ancestorAdded(AncestorEvent event) {
            event.getComponent().requestFocusInWindow();
        }
    });
    panel.add(nameTf, "wrap, growx, span");
    panel.add(new JLabel(Messages.getMessage("authenticator.password")));
    passTx = new JPasswordField(15);
    passTx.setText(getVfsUriParser().getPassword());
    panel.add(passTx, "wrap, growx,span");

    if (StringUtils.isNotBlank(getVfsUriParser().getUsername())) {
        nameTf.setSelectedItem(getVfsUriParser().getUsername());
    }
    if (names.length > 0) {
        nameTf.setSelectedIndex(0);
    }
    return panel;
}

From source file:uk.ac.ucl.cs.cmic.giftcloud.restserver.GiftCloudLoginDialog.java

public PasswordAuthentication getPasswordAuthentication(final String prompt) {
    // Set the default background colour to white
    UIManager UI = new UIManager();
    UI.put("OptionPane.background", Color.white);
    UI.put("Panel.background", Color.white);

    String defaultUserName = "";
    if (giftCloudProperties.getLastUserName().isPresent()) {
        defaultUserName = giftCloudProperties.getLastUserName().get();
    }// ww  w. ja v a  2s  .  c o  m

    // Create a panel for entering username and password
    final JPanel usernamePasswordPanel = new JPanel(new GridBagLayout());

    final JLabel promptField = new JLabel(prompt, SwingConstants.CENTER);
    final JTextField usernameField = new JTextField(defaultUserName, 16);
    final JPasswordField passwordField = new JPasswordField(16);

    // Add a special listener to get the focus onto the username field when the component is created, or password if the username has already been populated from the default value
    if (StringUtils.isBlank(defaultUserName)) {
        usernameField.addAncestorListener(new RequestFocusListener());
    } else {
        passwordField.addAncestorListener(new RequestFocusListener());
    }

    usernamePasswordPanel.add(promptField, promptConstraint);
    usernamePasswordPanel.add(new JLabel("Username:"), labelConstraint);
    usernamePasswordPanel.add(usernameField, fieldConstraint);
    usernamePasswordPanel.add(new JLabel("Password:"), labelConstraint);
    usernamePasswordPanel.add(passwordField, fieldConstraint);

    // Show the login dialog
    final int returnValue = JOptionPane.showConfirmDialog(new JDialog(getFrame(parent)), usernamePasswordPanel,
            LOGIN_DIALOG_TITLE, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon);

    if (JOptionPane.OK_OPTION == returnValue) {
        giftCloudProperties.setLastUserName(usernameField.getText());
        giftCloudProperties.setLastPassword(passwordField.getPassword());
        giftCloudProperties.save();

        return new PasswordAuthentication(usernameField.getText(), passwordField.getPassword());
    } else {
        return null;
    }
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Builds the GUI for the application/*  w w  w.j a  v  a  2s.  co m*/
 */
private void setup() {
    JPanel panel;
    JPanel gridPanel;
    JPanel outerPanel;
    JPanel flowPanel;
    JPanel boxedPanel;
    ButtonGroup bGroup;
    MaxHeightJScrollPane maxHeightJScrollPane;

    setupComponents();

    getContentPane().setLayout(new BorderLayout());

    // table.getTableHeader().setFont(new Font(table.getTableHeader().getFont().
    // getName(), table.getTableHeader().getFont().getStyle(),
    // MessageStyleFactory.instance().getFontSize()));
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);

    panel = new JPanel();
    panel.setLayout(new BorderLayout());

    outerPanel = new JPanel();
    outerPanel.setLayout(new BorderLayout());

    gridPanel = new JPanel();
    gridPanel.setLayout(new GridLayout(0, 1));

    gridPanel.add(connectString = new JComboBox());
    connectString.setEditable(true);
    gridPanel.add(querySelection = new JComboBox());
    querySelection.setEditable(false);
    querySelection.addActionListener(this);
    outerPanel.add(gridPanel, BorderLayout.NORTH);

    outerPanel.add(new JScrollPane(queryText = new JTextArea(QUERY_AREA_ROWS, QUERY_AREA_COLUMNS)),
            BorderLayout.SOUTH);
    queryText.setLineWrap(true);
    queryText.setWrapStyleWord(true);
    queryText.addKeyListener(this);

    panel.add(outerPanel, BorderLayout.CENTER);

    outerPanel = new JPanel();
    outerPanel.setLayout(new BorderLayout());

    boxedPanel = new JPanel();
    boxedPanel.setLayout(new GridLayout(0, 2));
    boxedPanel.add(new JLabel(Resources.getString("proUserId")));
    boxedPanel.add(userId = new JTextField(10));
    boxedPanel.add(new JLabel(Resources.getString("proPassword")));
    boxedPanel.add(password = new JPasswordField(10));
    outerPanel.add(boxedPanel, BorderLayout.WEST);

    // Prev/Next and the checkboxes are all on the flowPanel - Center of
    // outerPanel
    flowPanel = new JPanel();
    flowPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

    // Previous/Next buttons
    boxedPanel = new JPanel();
    boxedPanel.setLayout(new FlowLayout());
    boxedPanel.add(previousQuery = new JButton(Resources.getString("ctlPrev"),
            new ImageIcon(ImageUtility.getImageAsByteArray("ArrowLeftGreen.gif"))));
    previousQuery.setToolTipText(Resources.getString("tipPrev"));
    previousQuery.addActionListener(this);
    boxedPanel.add(nextQuery = new JButton(Resources.getString("ctlNext"),
            new ImageIcon(ImageUtility.getImageAsByteArray("ArrowRightGreen.gif"))));
    nextQuery.setToolTipText(Resources.getString("tipNext"));
    nextQuery.addActionListener(this);
    flowPanel.add(boxedPanel);

    // Checkboxes: Autocommit, Read Only and Pooling
    boxedPanel = new JPanel();
    boxedPanel.setLayout(new FlowLayout());
    boxedPanel.setBorder(getStandardBorder());
    boxedPanel.add(autoCommit = new JCheckBox(Resources.getString("ctlAutoCommit"), true));
    boxedPanel.add(readOnly = new JCheckBox(Resources.getString("ctlReadOnly"), false));
    boxedPanel.add(poolConnect = new JCheckBox(Resources.getString("ctlConnPool"), false));
    poolConnect.setEnabled(false);
    flowPanel.add(boxedPanel);
    outerPanel.add(flowPanel, BorderLayout.CENTER);

    boxedPanel = new JPanel();
    boxedPanel.setLayout(new GridLayout(0, 1));
    boxedPanel.setBorder(getStandardBorder());
    boxedPanel.add(runIndicator = new JLabel(Resources.getString("ctlRunning"), JLabel.CENTER));
    runIndicator.setForeground(Color.lightGray);
    boxedPanel.add(timeIndicator = new JLabel("", JLabel.RIGHT));
    outerPanel.add(boxedPanel, BorderLayout.EAST);

    panel.add(outerPanel, BorderLayout.NORTH);

    flowPanel = new JPanel();
    flowPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    boxedPanel = new JPanel();
    boxedPanel.setLayout(new FlowLayout());
    boxedPanel.setBorder(getStandardBorder());
    boxedPanel.add(new JLabel(Resources.getString("proQueryType")));
    boxedPanel.add(asQuery = new JRadioButton(Resources.getString("ctlSelect"), true));
    boxedPanel.add(asUpdate = new JRadioButton(Resources.getString("ctlUpdate")));
    boxedPanel.add(asDescribe = new JRadioButton(Resources.getString("ctlDescribe")));
    bGroup = new ButtonGroup();
    bGroup.add(asQuery);
    bGroup.add(asUpdate);
    bGroup.add(asDescribe);
    asQuery.addActionListener(this);
    asUpdate.addActionListener(this);
    asDescribe.addActionListener(this);
    flowPanel.add(boxedPanel);

    flowPanel.add(new JLabel("     "));

    boxedPanel = new JPanel();
    boxedPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
    boxedPanel.setBorder(getStandardBorder());
    boxedPanel.add(new JLabel(Resources.getString("proMaxRows")));
    boxedPanel.add(maxRows);
    flowPanel.add(boxedPanel);

    flowPanel.add(new JLabel("     "));

    flowPanel.add(execute = new JButton(Resources.getString("ctlExecute")));
    execute.addActionListener(this);
    flowPanel.add(remove = new JButton(Resources.getString("ctlRemove")));
    remove.addActionListener(this);
    flowPanel.add(commentToggle = new JButton(Resources.getString("ctlComment")));
    commentToggle.addActionListener(this);
    flowPanel.add(nextInList = new JButton(Resources.getString("ctlDown")));
    nextInList.addActionListener(this);

    panel.add(flowPanel, BorderLayout.SOUTH);

    getContentPane().add(panel, BorderLayout.NORTH);
    getRootPane().setDefaultButton(execute);

    messageDocument = new DefaultStyledDocument();
    getContentPane().add(
            maxHeightJScrollPane = new MaxHeightJScrollPane(message = new JTextPane(messageDocument)),
            BorderLayout.SOUTH);
    message.setEditable(false);

    loadedDBDriver = false;

    loadMenu();

    setupTextStyles();
    loadProperties();
    setupUserDefinedColoring();
    setupResultsTableColoring();
    loadConfig();
    loadConnectStrings();
    loadQueries();

    loadDrivers();

    // Check for avail of pool - enable/disable pooling option as appropriate
    // Not really useful until we get the pooling classes out of this code
    try {
        new GenericObjectPool(null);
        poolConnect.setEnabled(true);
        poolConnect.setSelected(true);
    } catch (Throwable any) {
        // No Apache Commons DB Pooling Library Found (DBCP)
        LOGGER.error(Resources.getString("errNoPoolLib"), any);
    }

    setDefaults();

    maxHeightJScrollPane.lockHeight(getHeight() / MAX_SCROLL_PANE_DIVISOR_FOR_MAX_HEIGHT);

    // Font
    setFontFromConfig(Configuration.instance());

    setVisible(true);
}

From source file:view.CertificateManagementDialog.java

private String getUserInputPassword() {
    JPanel panel = new JPanel();
    JLabel lblInsertPassword = new JLabel(Bundle.getBundle().getString("insertKeystorePassword"));
    JPasswordField pf = new JPasswordField(10);
    panel.add(lblInsertPassword);/*  w w w  . j av  a 2  s  .  co  m*/
    panel.add(pf);
    String[] options = new String[] { Bundle.getBundle().getString("btn.ok"),
            Bundle.getBundle().getString("btn.cancel") };
    int option = JOptionPane.showOptionDialog(null, panel, null, JOptionPane.NO_OPTION,
            JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
    if (option == JOptionPane.OK_OPTION) {
        char[] password = pf.getPassword();
        return new String(password);
    }
    return null;
}