Example usage for javax.swing JTextField getDocument

List of usage examples for javax.swing JTextField getDocument

Introduction

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

Prototype

public Document getDocument() 

Source Link

Document

Fetches the model associated with the editor.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.images.ImagesPane.java

/**
 * @return//from ww  w  .  jav  a 2 s .  co m
 */
private void createColObjSearch() {
    if (searchType != SearchType.FromRecordSet) {
        searchForAllAttachments();
        gridPanel.setItemList(rowsVector);
        JScrollPane sb = new JScrollPane(gridPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(sb, BorderLayout.CENTER);
        return;
    }

    CellConstraints cc = new CellConstraints();

    String rowDef = searchType != SearchType.FromRecordSet ? "f:p:g" : "p,4px,f:p:g";
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g,2px,p", rowDef));

    int y = 1;
    coVBP = new ViewBasedDisplayPanel(null, "COImageSearch", CollectionObject.class.getName(), true,
            MultiView.NO_SCROLLBARS | MultiView.IS_SINGLE_OBJ | MultiView.IS_EDITTING);
    pb.add(coVBP, cc.xyw(1, y, 3));
    y += 2;

    pb.add(gridPanel, cc.xyw(1, y, 3));

    coVBP.setData(dataMap);

    FormViewObj fvo = coVBP.getMultiView().getCurrentViewAsFormViewObj();
    JButton searchBtn = fvo.getCompById("2");
    JTextField textField = fvo.getCompById("1");
    y += 2;

    //fvo.setAlwaysGetDataFromUI(true);

    if (searchBtn != null) {
        final JButton searchBtnFinal = searchBtn;
        final JTextField textFieldFinal = textField;

        searchBtn.setEnabled(false);
        searchBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //searchForColObjImagesForTable();
                gridPanel.setItemList(rowsVector);
                //invalidate();
                //revalidate();
            }
        });

        textField.getDocument().addDocumentListener(new DocumentAdaptor() {
            @Override
            protected void changed(DocumentEvent e) {
                searchBtnFinal.setEnabled(textFieldFinal.getText().length() > 0);
            }
        });
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER && textFieldFinal.getText().length() > 0) {
                    //searchForColObjImagesForTable();
                }
            }

        });
    }
    JScrollPane sb = new JScrollPane(pb.getPanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    add(sb, BorderLayout.CENTER);
}

From source file:edu.ku.brc.af.auth.UserAndMasterPasswordMgr.java

/**
 * @return/*from  ww  w .  j a  v  a2  s.co m*/
 */
protected String[] getUserNamePasswordKey() {
    loadAndPushResourceBundle("masterusrpwd");

    FormLayout layout = new FormLayout("p, 4dlu, p, 8px, p", "p, 2dlu, p, 2dlu, p, 16px, p, 2dlu, p, 2dlu, p");
    layout.setRowGroups(new int[][] { { 1, 3, 5 } });

    PanelBuilder pb = new PanelBuilder(layout);

    final JTextField dbUsrTxt = createTextField(30);
    final JPasswordField dbPwdTxt = createPasswordField(30);
    final JTextField usrText = createTextField(30);
    final JPasswordField pwdText = createPasswordField(30);
    final char echoChar = pwdText.getEchoChar();

    final JLabel dbUsrLbl = createI18NFormLabel("USERNAME", SwingConstants.RIGHT);
    final JLabel dbPwdLbl = createI18NFormLabel("PASSWORD", SwingConstants.RIGHT);
    final JLabel usrLbl = createI18NFormLabel("USERNAME", SwingConstants.RIGHT);
    final JLabel pwdLbl = createI18NFormLabel("PASSWORD", SwingConstants.RIGHT);

    usrText.setText(usersUserName);

    CellConstraints cc = new CellConstraints();

    int y = 1;
    pb.addSeparator(UIRegistry.getResourceString("MASTER_SEP"), cc.xyw(1, y, 5));
    y += 2;

    pb.add(dbUsrLbl, cc.xy(1, y));
    pb.add(dbUsrTxt, cc.xy(3, y));
    y += 2;

    pb.add(dbPwdLbl, cc.xy(1, y));
    pb.add(dbPwdTxt, cc.xy(3, y));
    y += 2;

    pb.addSeparator(UIRegistry.getResourceString("USER_SEP"), cc.xyw(1, y, 5));
    y += 2;

    pb.add(usrLbl, cc.xy(1, y));
    pb.add(usrText, cc.xy(3, y));
    y += 2;

    pb.add(pwdLbl, cc.xy(1, y));
    pb.add(pwdText, cc.xy(3, y));

    pb.setDefaultDialogBorder();

    final CustomDialog dlg = new CustomDialog((Frame) null, getResourceString("MASTER_INFO_TITLE"), true,
            CustomDialog.OKCANCELAPPLYHELP, pb.getPanel());
    dlg.setOkLabel(getResourceString("GENERATE_KEY"));
    dlg.setHelpContext("MASTERPWD_GEN");
    dlg.setApplyLabel(showPwdLabel);

    dlg.createUI();
    dlg.getOkBtn().setEnabled(false);

    popResourceBundle();

    DocumentListener docListener = new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            String dbUserStr = dbUsrTxt.getText();

            boolean enable = !dbUserStr.isEmpty() && !((JTextField) dbPwdTxt).getText().isEmpty()
                    && !usrText.getText().isEmpty() && !((JTextField) pwdText).getText().isEmpty();
            if (enable && isNotEmpty(dbUserStr) && dbUserStr.equalsIgnoreCase("root")) {
                loadAndPushResourceBundle("masterusrpwd");
                UIRegistry.showLocalizedError("MASTER_NO_ROOT");
                popResourceBundle();
                enable = false;
            }
            dlg.getOkBtn().setEnabled(enable);
        }
    };

    dbUsrTxt.getDocument().addDocumentListener(docListener);
    dbPwdTxt.getDocument().addDocumentListener(docListener);
    usrText.getDocument().addDocumentListener(docListener);
    pwdText.getDocument().addDocumentListener(docListener);

    currEcho = echoChar;

    dlg.getApplyBtn().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dlg.getApplyBtn().setText(currEcho == echoChar ? hidePwdLabel : showPwdLabel);
            currEcho = currEcho == echoChar ? 0 : echoChar;
            pwdText.setEchoChar(currEcho);
            dbPwdTxt.setEchoChar(currEcho);
        }
    });

    dlg.setVisible(true);
    if (!dlg.isCancelled()) {
        return new String[] { dbUsrTxt.getText(), ((JTextField) dbPwdTxt).getText(), usrText.getText(),
                ((JTextField) pwdText).getText() };
    }

    return null;
}

From source file:edu.ku.brc.af.auth.UserAndMasterPasswordMgr.java

/**
 * Displays a dialog used for editing the Master Username and Password.
 * @param isLocal whether u/p is stored locally or not
 * @param usrName// w  ww  .  jav a 2  s  . c o  m
 * @param dbName
 * @param masterPath the path to the password
 * @return whether to ask for the information because it wasn't found
 */
protected boolean askForInfo(final Boolean isLocal, final String usrName, final String dbName,
        final String masterPath) {
    loadAndPushResourceBundle("masterusrpwd");

    FormLayout layout = new FormLayout("p, 2px, f:p:g, 4px, p, 4px, p, 4px, p", "p,2px,p,2px,p,2dlu,p,2dlu,p");

    PanelBuilder pb = new PanelBuilder(layout);
    pb.setDefaultDialogBorder();

    ButtonGroup group = new ButtonGroup();
    final JRadioButton isNetworkRB = new JRadioButton(getResourceString("IS_NET_BASED"));
    final JRadioButton isPrefBasedRB = new JRadioButton(getResourceString("IS_ENCRYPTED_KEY"));
    isPrefBasedRB.setSelected(true);
    group.add(isNetworkRB);
    group.add(isPrefBasedRB);

    final JTextField keyTxt = createTextField(35);
    final JTextField urlTxt = createTextField(35);
    final JLabel keyLbl = createI18NFormLabel("ENCRYPTED_USRPWD");
    final JLabel urlLbl = createI18NFormLabel("URL");
    final JButton createBtn = createI18NButton("CREATE_KEY");

    final JButton copyCBBtn = createIconBtn("ClipboardCopy", IconManager.IconSize.Std24, "CPY_TO_CB_TT", null);
    final JButton pasteCBBtn = createIconBtn("ClipboardPaste", IconManager.IconSize.Std24, "CPY_FROM_CB_TT",
            null);

    // retrieves the encrypted key for the current settings in the dialog
    String dbNameFromForm = AppPreferences.getLocalPrefs().get("login.databases_selected", null);
    if (isNotEmpty(dbNameFromForm) && isNotEmpty(usersUserName)) {
        String masterKey = getMasterPrefPath(usersUserName, dbNameFromForm, true);
        if (isNotEmpty(masterKey)) {
            String encryptedKey = AppPreferences.getLocalPrefs().get(masterKey, null);
            if (isNotEmpty(encryptedKey) && !encryptedKey.startsWith("http")) {
                keyTxt.setText(encryptedKey);
            }
        }
    }

    CellConstraints cc = new CellConstraints();

    int y = 1;
    pb.add(createI18NFormLabel("MASTER_LOC"), cc.xywh(1, y, 1, 3));
    pb.add(isPrefBasedRB, cc.xy(3, y));
    y += 2;
    pb.add(isNetworkRB, cc.xy(3, y));
    y += 2;

    pb.addSeparator("", cc.xyw(1, y, 9));
    y += 2;
    pb.add(keyLbl, cc.xy(1, y));
    pb.add(keyTxt, cc.xy(3, y));
    pb.add(createBtn, cc.xy(5, y));
    pb.add(copyCBBtn, cc.xy(7, y));
    pb.add(pasteCBBtn, cc.xy(9, y));
    y += 2;

    pb.add(urlLbl, cc.xy(1, y));
    pb.add(urlTxt, cc.xy(3, y));
    y += 2;

    boolean isEditMode = isLocal != null && isNotEmpty(masterPath);
    if (isEditMode) {
        isPrefBasedRB.setSelected(isLocal);
        if (isLocal) {
            keyTxt.setText(masterPath);
        } else {
            urlTxt.setText(masterPath);
        }
    }

    copyCBBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Copy to Clipboard
            UIHelper.setTextToClipboard(keyTxt.getText());
        }
    });

    pasteCBBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            keyTxt.setText(UIHelper.getTextFromClipboard());
        }
    });

    final CustomDialog dlg = new CustomDialog((Frame) null, getResourceString("MASTER_TITLE"), true,
            CustomDialog.OKCANCELHELP, pb.getPanel());
    if (!isEditMode) {
        dlg.setOkLabel(getResourceString("CONT"));
        dlg.setCancelLabel(getResourceString("BACK"));
    }
    dlg.setHelpContext("MASTERPWD_MAIN");
    dlg.createUI();
    dlg.getOkBtn().setEnabled(false);
    urlLbl.setEnabled(false);
    urlTxt.setEnabled(false);
    copyCBBtn.setEnabled(true);
    pasteCBBtn.setEnabled(true);

    DocumentListener dl = new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            dlg.getOkBtn().setEnabled((isPrefBasedRB.isSelected() && !keyTxt.getText().isEmpty())
                    || (isNetworkRB.isSelected() && !urlTxt.getText().isEmpty()));
        }
    };
    keyTxt.getDocument().addDocumentListener(dl);
    urlTxt.getDocument().addDocumentListener(dl);

    ChangeListener chgListener = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean isNet = isNetworkRB.isSelected();
            keyLbl.setEnabled(!isNet);
            keyTxt.setEnabled(!isNet);
            createBtn.setEnabled(!isNet);
            copyCBBtn.setEnabled(!isNet);
            pasteCBBtn.setEnabled(!isNet);
            urlLbl.setEnabled(isNet);
            urlTxt.setEnabled(isNet);
            dlg.getOkBtn().setEnabled((isPrefBasedRB.isSelected() && !keyTxt.getText().isEmpty())
                    || (isNetworkRB.isSelected() && !urlTxt.getText().isEmpty()));
        }
    };

    isNetworkRB.addChangeListener(chgListener);
    isPrefBasedRB.addChangeListener(chgListener);

    boolean isPref = AppPreferences.getLocalPrefs().getBoolean(getIsLocalPrefPath(usrName, dbName, true), true);
    isNetworkRB.setSelected(!isPref);
    isPrefBasedRB.setSelected(isPref);

    createBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String[] keys = getUserNamePasswordKey();
            if (keys != null && keys.length == 4) {
                String encryptedStr = encrypt(keys[0], keys[1], keys[3]);
                if (encryptedStr != null) {
                    keyTxt.setText(encryptedStr);
                    dlg.getOkBtn().setEnabled(true);

                    usersUserName = keys[2];
                }
            }
        }
    });

    popResourceBundle();

    dlg.setVisible(true);

    if (!dlg.isCancelled()) {
        String value;
        if (isNetworkRB.isSelected()) {
            value = StringEscapeUtils.escapeHtml(urlTxt.getText());
        } else {
            value = keyTxt.getText();
        }

        AppPreferences.getLocalPrefs().putBoolean(getIsLocalPrefPath(usrName, dbName, true),
                !isNetworkRB.isSelected());
        AppPreferences.getLocalPrefs().put(getMasterPrefPath(usrName, dbName, true), value);
        return true;
    }
    return false;
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }/*from  w  w  w .ja  va  2  s  . c  om*/
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void testFilter(FilterTestType testType)
        throws BadLocationException, InterruptedException, ReflectiveOperationException {
    MainGui mainGui = new MainGui(mockManyBrowsersPanel);
    mainGui.setMainCallbacks(mockMainCallbacks);

    Mockito.when(mockConfiguration.useSpanTable()).thenReturn(testType == CHANGE_TEXT);

    mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
    mainGui.initializeGui(TestUtilities.getSixTestArticles());

    waitForGuiTasks();// w  ww . j ava 2s.  c o  m

    JTable table = (JTable) findComponent(mockContentPane, JTable.class);
    assertNotNull(table);

    assertEquals(mockConfiguration.useSpanTable() ? 12 : 6, table.getRowCount());

    JTextField filterTextField = (JTextField) findComponent(mockContentPane, JTextField.class);
    assertNotNull(filterTextField);
    AbstractDocument document = (AbstractDocument) filterTextField.getDocument();

    document.insertString(0, "title:title1", null);

    assertEquals(mockConfiguration.useSpanTable() ? 2 : 1, table.getRowCount());

    if (testType == REMOVE_TEXT) {
        document.remove(0, document.getLength());
    } else if (testType == CHANGE_TEXT) {
        document.replace(6, 6, "title2", null);

        // Since change is implemented as remove and insert, the fireChangedUpdate method is called with reflection.
        AbstractDocument.DefaultDocumentEvent mockEvent = Mockito
                .mock(AbstractDocument.DefaultDocumentEvent.class);
        Method method = AbstractDocument.class.getDeclaredMethod("fireChangedUpdate", DocumentEvent.class);
        method.setAccessible(true);
        method.invoke(document, mockEvent);
    } else if (testType == NO_MATCHES) {
        document.insertString(document.getLength(), "-some-nonsense", null);
    }

    checkArticlesInGui(testType, mainGui, table.getRowCount());
}

From source file:openlr.mapviewer.coding.ui.AbstractCodingOptionsDialog.java

/**
 * Sets up an input field of the form// ww w. ja va 2s .  c o  m
 * 
 * @param propKey
 *            The full configuration property key this field relates to
 * @param value
 *            The initial value to set
 * @return The set-up input field
 */
private JTextField createInputField(final String propKey, final String value) {

    final JTextField valueField = new JTextField();
    valueField.setText(value);
    valueField.setHorizontalAlignment(JTextField.RIGHT);
    valueField.setPreferredSize(new Dimension(WIDT_INPUT_FIELD, valueField.getHeight()));
    optionsTextFields.put(propKey, valueField);

    final String defaultValue = defaultConfig.getString(propKey);
    valueField.getDocument().addDocumentListener(new VisualPropertyChangeListener(valueField, defaultValue));
    if (!defaultValue.equals(value)) {
        valueField.setBackground(VisualPropertyChangeListener.COLOR_FIELD_VALUE_DIFF_DEFAULT);
    }
    StringBuilder toolTip = new StringBuilder();
    toolTip.append(propKey).append(", default: ").append(defaultValue);

    valueField.setToolTipText(toolTip.toString());

    afterInputFieldCreation(propKey, valueField);

    return valueField;
}

From source file:org.languagetool.gui.ConfigurationDialog.java

private void createOfficeElements(GridBagConstraints cons, JPanel portPanel) {
    int numParaCheck = config.getNumParasToCheck();
    JRadioButton[] radioButtons = new JRadioButton[3];
    ButtonGroup numParaGroup = new ButtonGroup();
    radioButtons[0] = new JRadioButton(Tools.getLabel(messages.getString("guiCheckOnlyParagraph")));
    radioButtons[0].setActionCommand("ParagraphCheck");

    radioButtons[1] = new JRadioButton(Tools.getLabel(messages.getString("guiCheckFullText")));
    radioButtons[1].setActionCommand("FullTextCheck");

    radioButtons[2] = new JRadioButton(Tools.getLabel(messages.getString("guiCheckNumParagraphs")));
    radioButtons[2].setActionCommand("NParagraphCheck");
    radioButtons[2].setSelected(true);//  w ww .j  a  va2  s. c  om

    JTextField numParaField = new JTextField(Integer.toString(5), 2);
    numParaField.setEnabled(radioButtons[2].isSelected());
    numParaField.setMinimumSize(new Dimension(30, 25));

    for (int i = 0; i < 3; i++) {
        numParaGroup.add(radioButtons[i]);
    }

    if (numParaCheck == 0) {
        radioButtons[0].setSelected(true);
        numParaField.setEnabled(false);
    } else if (numParaCheck < 0) {
        radioButtons[1].setSelected(true);
        numParaField.setEnabled(false);
    } else {
        radioButtons[2].setSelected(true);
        numParaField.setText(Integer.toString(numParaCheck));
        numParaField.setEnabled(true);
    }

    radioButtons[0].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            numParaField.setEnabled(false);
            config.setNumParasToCheck(0);
        }
    });

    radioButtons[1].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            numParaField.setEnabled(false);
            config.setNumParasToCheck(-1);
        }
    });

    radioButtons[2].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int numParaCheck = Integer.parseInt(numParaField.getText());
            if (numParaCheck < 1)
                numParaCheck = 1;
            else if (numParaCheck > 99)
                numParaCheck = 99;
            config.setNumParasToCheck(numParaCheck);
            numParaField.setForeground(Color.BLACK);
            numParaField.setText(Integer.toString(numParaCheck));
            numParaField.setEnabled(true);
        }
    });

    numParaField.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            try {
                int numParaCheck = Integer.parseInt(numParaField.getText());
                if (numParaCheck > 0 && numParaCheck < 99) {
                    numParaField.setForeground(Color.BLACK);
                    config.setNumParasToCheck(numParaCheck);
                } else {
                    numParaField.setForeground(Color.RED);
                }
            } catch (NumberFormatException ex) {
                numParaField.setForeground(Color.RED);
            }
        }
    });

    JLabel textChangedLabel = new JLabel(Tools.getLabel(messages.getString("guiTextChangeLabel")));
    cons.gridy++;
    portPanel.add(textChangedLabel, cons);

    cons.gridy++;
    cons.insets = new Insets(0, 30, 0, 0);
    for (int i = 0; i < 3; i++) {
        portPanel.add(radioButtons[i], cons);
        if (i < 2)
            cons.gridy++;
    }
    cons.gridx = 1;
    portPanel.add(numParaField, cons);

    JCheckBox noMultiResetbox = new JCheckBox(Tools.getLabel(messages.getString("guiNoMultiReset")));
    noMultiResetbox.setSelected(config.isNoMultiReset());
    noMultiResetbox.setEnabled(config.isResetCheck());
    noMultiResetbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            config.setNoMultiReset(noMultiResetbox.isSelected());
        }
    });

    JCheckBox resetCheckbox = new JCheckBox(Tools.getLabel(messages.getString("guiDoResetCheck")));
    resetCheckbox.setSelected(config.isResetCheck());
    resetCheckbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            config.setDoResetCheck(resetCheckbox.isSelected());
            noMultiResetbox.setEnabled(resetCheckbox.isSelected());
        }
    });
    cons.insets = new Insets(0, 4, 0, 0);
    cons.gridx = 0;
    //    JLabel dummyLabel = new JLabel(" ");
    //    cons.gridy++;
    //    portPanel.add(dummyLabel, cons);
    cons.gridy++;
    portPanel.add(resetCheckbox, cons);

    cons.insets = new Insets(0, 30, 0, 0);
    cons.gridx = 0;
    cons.gridy++;
    portPanel.add(noMultiResetbox, cons);

    JCheckBox fullTextCheckAtFirstBox = new JCheckBox(
            Tools.getLabel(messages.getString("guiCheckFullTextAtFirst")));
    fullTextCheckAtFirstBox.setSelected(config.doFullCheckAtFirst());
    fullTextCheckAtFirstBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            config.setFullCheckAtFirst(fullTextCheckAtFirstBox.isSelected());
        }
    });
    cons.insets = new Insets(0, 4, 0, 0);
    cons.gridx = 0;
    //    cons.gridy++;
    //    JLabel dummyLabel2 = new JLabel(" ");
    //    portPanel.add(dummyLabel2, cons);
    cons.gridy++;
    portPanel.add(fullTextCheckAtFirstBox, cons);

    JCheckBox isMultiThreadBox = new JCheckBox(Tools.getLabel(messages.getString("guiIsMultiThread")));
    isMultiThreadBox.setSelected(config.isMultiThread());
    isMultiThreadBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            config.setMultiThreadLO(isMultiThreadBox.isSelected());
        }
    });
    cons.gridy++;
    JLabel dummyLabel3 = new JLabel(" ");
    portPanel.add(dummyLabel3, cons);
    cons.gridy++;
    portPanel.add(isMultiThreadBox, cons);

}

From source file:org.languagetool.gui.ConfigurationDialog.java

private JPanel getSpecialRuleValuePanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints cons = new GridBagConstraints();
    cons.gridx = 0;//  w  w  w.  j  a v  a 2 s. c  o  m
    cons.gridy = 0;
    cons.weightx = 0.0f;
    cons.anchor = GridBagConstraints.WEST;

    List<JCheckBox> ruleCheckboxes = new ArrayList<JCheckBox>();
    List<JLabel> ruleLabels = new ArrayList<JLabel>();
    List<JTextField> ruleValueFields = new ArrayList<JTextField>();

    for (int i = 0; i < configurableRules.size(); i++) {
        Rule rule = configurableRules.get(i);
        JCheckBox ruleCheckbox = new JCheckBox(rule.getDescription());
        ruleCheckboxes.add(ruleCheckbox);
        ruleCheckbox.setSelected(getEnabledState(rule));
        cons.insets = new Insets(3, 0, 0, 0);
        panel.add(ruleCheckbox, cons);

        cons.insets = new Insets(0, 24, 0, 0);
        cons.gridy++;
        JLabel ruleLabel = new JLabel(rule.getConfigureText());
        ruleLabels.add(ruleLabel);
        ruleLabel.setEnabled(ruleCheckbox.isSelected());
        panel.add(ruleLabel, cons);

        cons.gridx++;
        int value = config.getConfigurableValue(rule.getId());
        if (config.getConfigurableValue(rule.getId()) < 0) {
            value = rule.getDefaultValue();
        }
        JTextField ruleValueField = new JTextField(Integer.toString(value), 2);
        ruleValueFields.add(ruleValueField);
        ruleValueField.setEnabled(ruleCheckbox.isSelected());
        ruleValueField.setMinimumSize(new Dimension(35, 25)); // without this the box is just a few pixels small, but why?
        panel.add(ruleValueField, cons);

        ruleCheckbox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
                ruleValueField.setEnabled(ruleCheckbox.isSelected());
                ruleLabel.setEnabled(ruleCheckbox.isSelected());
                if (ruleCheckbox.isSelected()) {
                    config.getEnabledRuleIds().add(rule.getId());
                    config.getDisabledRuleIds().remove(rule.getId());
                } else {
                    config.getEnabledRuleIds().remove(rule.getId());
                    config.getDisabledRuleIds().add(rule.getId());
                }
            }
        });

        ruleValueField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                changedUpdate(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                changedUpdate(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                try {
                    int num = Integer.parseInt(ruleValueField.getText());
                    if (num < rule.getMinConfigurableValue()) {
                        num = rule.getMinConfigurableValue();
                        ruleValueField.setForeground(Color.RED);
                    } else if (num > rule.getMaxConfigurableValue()) {
                        num = rule.getMaxConfigurableValue();
                        ruleValueField.setForeground(Color.RED);
                    } else {
                        ruleValueField.setForeground(null);
                    }
                    config.setConfigurableValue(rule.getId(), num);
                } catch (Exception ex) {
                    ruleValueField.setForeground(Color.RED);
                }
            }
        });

        cons.gridx = 0;
        cons.gridy++;

    }
    return panel;
}

From source file:org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement.java

public SQLComponent createComponent() {
    return new BaseSQLComponent(this) {

        private Icon iconWarning = ImageIconWarning.getInstance();

        public void addViews() {
            this.setLayout(new GridBagLayout());
            final GridBagConstraints c = new DefaultGridBagConstraints();

            Set<Class<? extends SQLElement>> s = map.keySet();

            final ArrayList<Class<? extends SQLElement>> list = new ArrayList<Class<? extends SQLElement>>(s);
            Collections.sort(list, new Comparator<Class<? extends SQLElement>>() {
                public int compare(Class<? extends SQLElement> o1, Class<? extends SQLElement> o2) {
                    return o1.getSimpleName().toString().compareTo(o2.getSimpleName().toString());
                };//from   www .jav a  2 s.  c  o  m
            });

            List<String> added = new ArrayList<String>();
            for (Class<? extends SQLElement> class1 : list) {
                String prefix = map.get(class1);
                if (!added.contains(prefix)) {
                    c.gridy++;
                    c.gridx = 0;
                    c.weightx = 0;
                    added.add(prefix);
                    SQLElement elt = Configuration.getInstance().getDirectory().getElement(class1);
                    if (elt == null) {
                        throw new IllegalArgumentException("Element null for class " + class1);
                    }
                    // Avoir
                    JLabel labelAvoirFormat = new JLabel(
                            StringUtils.firstUp(elt.getPluralName()) + " " + getLabelFor(prefix + FORMAT),
                            SwingConstants.RIGHT);
                    this.add(labelAvoirFormat, c);
                    c.gridx++;
                    c.weightx = 1;
                    final JTextField fieldFormat = new JTextField();
                    this.add(fieldFormat, c);

                    final JLabel labelAvoirStart = new JLabel(getLabelFor(prefix + START));
                    c.gridx++;
                    c.weightx = 0;
                    this.add(labelAvoirStart, c);
                    c.gridx++;
                    c.weightx = 1;
                    final JTextField fieldStart = new JTextField();
                    this.add(fieldStart, c);

                    final JLabel labelResult = new JLabel();
                    c.gridx++;
                    c.weightx = 0;
                    this.add(labelResult, c);

                    if (getTable().getFieldsName().contains(prefix + AUTO_MONTH)) {
                        final JCheckBox boxAuto = new JCheckBox(getLabelFor(prefix + AUTO_MONTH));
                        c.gridx++;
                        c.weightx = 0;
                        this.add(boxAuto, c);
                        this.addSQLObject(boxAuto, prefix + AUTO_MONTH);
                    }
                    // Affichage dynamique du rsultat
                    SimpleDocumentListener listener = new SimpleDocumentListener() {

                        @Override
                        public void update(DocumentEvent e) {
                            updateLabel(fieldStart, fieldFormat, labelResult);

                        }
                    };

                    fieldFormat.getDocument().addDocumentListener(listener);
                    fieldStart.getDocument().addDocumentListener(listener);

                    this.addRequiredSQLObject(fieldFormat, prefix + FORMAT);
                    this.addRequiredSQLObject(fieldStart, prefix + START);
                }
            }

            // JLabel labelCodeLettrage = new JLabel(getLabelFor("CODE_LETTRAGE"));
            // c.gridy++;
            // c.gridx = 0;
            // c.weightx = 0;
            // this.add(labelCodeLettrage, c);
            // c.gridx++;
            // c.weightx = 1;
            // this.add(this.textCodeLettrage, c);
            //
            // c.gridx++;
            // c.weightx = 0;
            // labelNextCodeLettrage = new JLabel();
            // this.add(labelNextCodeLettrage, c);

            JLabel labelExemple = new JLabel("Exemple de format : 'Fact'yyyy0000");
            c.gridy++;
            c.gridx = 0;
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.weighty = 1;
            c.anchor = GridBagConstraints.NORTHWEST;
            this.add(labelExemple, c);

            // this.textCodeLettrage.getDocument().addDocumentListener(this.listenText);

        }

        // private void updateLabelNextCode() {
        // String s = getNextCodeLetrrage(this.textCodeLettrage.getText());
        // this.labelNextCodeLettrage.setText(donne + " " + s);
        // }

        private void updateLabel(JTextField textStart, JTextField textFormat, JLabel label) {
            if (textStart.getText().trim().length() > 0) {
                try {
                    String numProposition = getNextNumero(textFormat.getText(),
                            Integer.parseInt(textStart.getText()), new Date());

                    if (numProposition != null) {
                        label.setText(" --> " + numProposition);
                        label.setIcon(null);
                    } else {
                        label.setIcon(this.iconWarning);
                        label.setText("");
                    }
                } catch (IllegalArgumentException e) {
                    JOptionPane.showMessageDialog(null,
                            "Le format " + textFormat.getText() + " n'est pas valide!");
                }
            } else {
                label.setIcon(this.iconWarning);
                label.setText("");
            }
        }

    };
}

From source file:org.openmicroscopy.shoola.agents.metadata.editor.UserProfile.java

/**
 * Builds the panel hosting the user's details.
 * //w  w w.  jav  a 2 s  .c o  m
 * @return See above.
 */
private JPanel buildContentPanel() {
    ExperimenterData user = (ExperimenterData) model.getRefObject();
    boolean editable = model.isUserOwner(user);
    if (!editable)
        editable = MetadataViewerAgent.isAdministrator();
    details = EditorUtil.convertExperimenter(user);
    JPanel content = new JPanel();
    content.setBorder(BorderFactory.createTitledBorder("User"));
    content.setBackground(UIUtilities.BACKGROUND_COLOR);
    Entry<String, String> entry;
    Iterator<Entry<String, String>> i = details.entrySet().iterator();
    JComponent label;
    JTextField area;
    String key, value;
    content.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(0, 2, 2, 0);
    //Add log in name but cannot edit.
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = GridBagConstraints.REMAINDER;//end row
    c.fill = GridBagConstraints.HORIZONTAL;
    content.add(buildProfileCanvas(), c);
    c.gridy++;
    c.gridx = 0;
    label = EditorUtil.getLabel(EditorUtil.DISPLAY_NAME, true);
    label.setBackground(UIUtilities.BACKGROUND_COLOR);
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE;//reset to default
    c.weightx = 0.0;
    content.add(label, c);
    c.gridx++;
    content.add(Box.createHorizontalStrut(5), c);
    c.gridx++;
    c.gridwidth = GridBagConstraints.REMAINDER;//end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    loginArea.setText(user.getUserName());
    loginArea.setEnabled(false);
    loginArea.setEditable(false);
    if (MetadataViewerAgent.isAdministrator() && !model.isSystemUser(user.getId()) && !model.isSelf()) {
        loginArea.setEnabled(true);
        loginArea.getDocument().addDocumentListener(this);
    }
    content.add(loginArea, c);
    while (i.hasNext()) {
        ++c.gridy;
        c.gridx = 0;
        entry = i.next();
        key = entry.getKey();
        value = entry.getValue();
        label = EditorUtil.getLabel(key, EditorUtil.FIRST_NAME.equals(key) || EditorUtil.LAST_NAME.equals(key));
        area = new JTextField(value);
        area.setBackground(UIUtilities.BACKGROUND_COLOR);
        area.setEditable(editable);
        area.setEnabled(editable);
        if (editable)
            area.getDocument().addDocumentListener(this);
        items.put(key, area);
        label.setBackground(UIUtilities.BACKGROUND_COLOR);
        c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
        c.fill = GridBagConstraints.NONE;//reset to default
        c.weightx = 0.0;
        content.add(label, c);
        c.gridx++;
        content.add(Box.createHorizontalStrut(5), c);
        c.gridx++;
        c.gridwidth = GridBagConstraints.REMAINDER;//end row
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;
        content.add(area, c);
    }
    c.gridx = 0;
    c.gridy++;
    label = EditorUtil.getLabel(EditorUtil.DEFAULT_GROUP, false);
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE;//reset to default
    c.weightx = 0.0;
    content.add(label, c);
    c.gridx++;
    content.add(Box.createHorizontalStrut(5), c);
    c.gridx++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    content.add(groupsBox, c);
    c.gridy++;
    content.add(permissionsPane, c);
    c.gridx = 0;
    c.gridy++;
    label = EditorUtil.getLabel(EditorUtil.GROUP_OWNER, false);
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0;
    content.add(label, c);
    c.gridx++;
    content.add(Box.createHorizontalStrut(5), c);
    c.gridx++;
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.NONE;
    c.weightx = 1.0;
    content.add(ownerBox, c);
    if (activeBox.isVisible()) {
        c.gridx = 0;
        c.gridy++;
        label = EditorUtil.getLabel(EditorUtil.ACTIVE, false);
        c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
        c.fill = GridBagConstraints.NONE;
        c.weightx = 0.0;
        content.add(label, c);
        c.gridx++;
        content.add(Box.createHorizontalStrut(5), c);
        c.gridx++;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.NONE;
        c.weightx = 1.0;
        content.add(activeBox, c);
    }
    if (adminBox.isVisible()) {
        c.gridx = 0;
        c.gridy++;
        label = EditorUtil.getLabel(EditorUtil.ADMINISTRATOR, false);
        c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
        c.fill = GridBagConstraints.NONE;
        c.weightx = 0.0;
        content.add(label, c);
        c.gridx++;
        content.add(Box.createHorizontalStrut(5), c);
        c.gridx++;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.NONE;
        c.weightx = 1.0;
        content.add(adminBox, c);
    }
    c.gridx = 0;
    c.gridy++;
    content.add(Box.createHorizontalStrut(10), c);
    c.gridy++;
    label = UIUtilities.setTextFont(EditorUtil.MANDATORY_DESCRIPTION, Font.ITALIC);
    label.setForeground(UIUtilities.REQUIRED_FIELDS_COLOR);
    c.weightx = 0.0;
    content.add(label, c);
    return content;
}