Example usage for javax.swing.event DocumentListener DocumentListener

List of usage examples for javax.swing.event DocumentListener DocumentListener

Introduction

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

Prototype

DocumentListener

Source Link

Usage

From source file:org.nuclos.client.wizard.steps.NuclosEntityAttributeCommonPropertiesStep.java

@Override
protected void initComponents() {
    double size[][] = { { 150, 20, TableLayout.FILL },
            { 20, 20, 20, 20, 20, 20, 20, 20, 90, TableLayout.FILL } };

    TableLayout layout = new TableLayout(size);
    layout.setVGap(3);/*from   w  ww . j  a va2 s  .  c o m*/
    layout.setHGap(5);
    this.setLayout(layout);

    final LabeledComponentSupport support = new LabeledComponentSupport();

    lbLabel = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.10", "Feldname")
                    + ": ");
    tfLabel = new JTextField();
    tfLabel.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());
    tfLabel.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.10", "Feldname"));

    lbDefaultValue = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.11", "Standardwert")
                    + ": ");
    tfDefaultValue = new JTextField();
    tfDefaultValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.11", "Standardwert"));
    tfDefaultValue.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());

    cbxDefaultValue = new JComboBox();
    cbxDefaultValue.setVisible(false);
    cbxDefaultValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.11", "Standardwert"));

    lovDefaultValue = new ListOfValues();
    lovDefaultValue.setVisible(false);
    lovDefaultValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.11", "Standardwert"));

    dateDefaultValue = new DateChooser(support, true);
    dateDefaultValue.setVisible(false);
    dateDefaultValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.11", "Standardwert"));

    cbDefaultValue = new JCheckBox();
    cbDefaultValue.setVisible(false);
    cbDefaultValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.11", "Standardwert"));

    lbDistinct = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.7", "Eindeutig")
                    + ": ");
    cbDistinct = new JCheckBox();
    cbDistinct.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.7", "Eindeutig"));

    lbLogBook = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.8", "Logbuch")
                    + ": ");
    cbLogBook = new JCheckBox();
    cbLogBook.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.8", "Logbuch"));

    lbMandatory = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.9", "Pflichtfeld")
                    + ": ");
    cbMandatory = new JCheckBox();
    cbMandatory.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.9", "Pflichtfeld"));

    tfMandatory = new JTextField();
    tfMandatory.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());
    tfMandatory.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.27", "Defaultwert fr Pflichtfeld"));

    cbxMandatory = new JComboBox();
    cbxMandatory.setVisible(false);
    cbxMandatory.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.27", "Defaultwert fr Pflichtfeld"));

    lovMandatory = new ListOfValues();
    lovMandatory.setVisible(false);
    lovMandatory.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.27", "Defaultwert fr Pflichtfeld"));

    dateMandatory = new DateChooser(support);
    dateMandatory.setVisible(false);
    dateMandatory.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.27", "Defaultwert fr Pflichtfeld"));

    cbMandatoryValue = new JCheckBox();
    cbMandatoryValue.setVisible(false);
    cbMandatoryValue.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.27", "Defaultwert fr Pflichtfeld"));

    lbDBFieldName = new JLabel(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.12", "DB-Spaltename"));
    tfDBFieldName = new JTextField();
    tfDBFieldName.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.12", "DB-Spaltename"));
    tfDBFieldName.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());

    lbDBFieldNameComplete = new JLabel(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.18", "Vollst\u00e4ndiger Spaltenname"));
    tfDBFieldNameComplete = new JTextField();
    tfDBFieldNameComplete.setEnabled(false);

    lbAttributeGroup = new JLabel(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.19", "Attributegruppe"));
    cbxAttributeGroup = new JComboBox();
    cbxAttributeGroup.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.19", "Attributegruppe"));

    lbCalcFunction = new JLabel(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.20", "Berechungsvorschrift"));
    cbxCalcFunction = new JComboBox();
    cbxCalcFunction.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.20", "Berechungsvorschrift"));

    lbCalculationScript = new JLabel(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.calculationscript.label", "Berechnungsausdruck"));
    lbCalculationScript.setToolTipText(SpringLocaleDelegate.getInstance().getMessage(
            "wizard.step.attributeproperties.calculationscript.description", "Berechnungsausdruck"));
    btCalculationScript = new JButton("...");
    btCalculationScript.setToolTipText(SpringLocaleDelegate.getInstance().getMessage(
            "wizard.step.attributeproperties.calculationscript.description", "Berechnungsausdruck"));
    btCalculationScript.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ScriptEditor editor = new ScriptEditor();
            if (getModel().getAttribute().getCalculationScript() != null) {
                editor.setScript(getModel().getAttribute().getCalculationScript());
            }
            editor.run();
            NuclosScript script = editor.getScript();
            if (org.nuclos.common2.StringUtils.isNullOrEmpty(script.getSource())) {
                script = null;
            }
            getModel().getAttribute().setCalculationScript(script);
        }
    });

    lbIndexed = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributeproperties.26", "Indiziert"));
    cbIndexed = new JCheckBox();
    cbIndexed.setToolTipText(SpringLocaleDelegate.getInstance()
            .getMessage("wizard.step.attributeproperties.tooltip.26", "Indiziert"));

    pnlMoreOptions = new JPanel();

    double sizeMoreOptions[][] = { { 150, TableLayout.FILL }, { 20, 20, 20, TableLayout.FILL } };

    TableLayout tlMoreOptions = new TableLayout(sizeMoreOptions);
    tlMoreOptions.setVGap(3);
    tlMoreOptions.setHGap(5);

    pnlMoreOptions.setLayout(tlMoreOptions);
    pnlMoreOptions.add(lbDBFieldName, "0,0");
    pnlMoreOptions.add(tfDBFieldName, "1,0");
    pnlMoreOptions.add(lbDBFieldNameComplete, "0,1");
    pnlMoreOptions.add(tfDBFieldNameComplete, "1,1");
    pnlMoreOptions.add(lbIndexed, "0,2");
    pnlMoreOptions.add(cbIndexed, "1,2");

    MoreOptionPanel optionPanel = new MoreOptionPanel(pnlMoreOptions);

    this.add(lbLabel, "0,0");
    this.add(tfLabel, "1,0 , 2,0");
    this.add(lbDefaultValue, "0,1");
    this.add(tfDefaultValue, "1,1 , 2,1");
    this.add(cbxDefaultValue, "1,1 , 2,1");
    this.add(lovDefaultValue, "1,1 , 2,1");
    this.add(dateDefaultValue, "1,1 , 2,1");
    this.add(cbDefaultValue, "1,1");
    this.add(lbDistinct, "0,2");
    this.add(cbDistinct, "1,2");
    this.add(lbLogBook, "0,3");
    this.add(cbLogBook, "1,3");
    this.add(lbMandatory, "0,4");
    this.add(cbMandatory, "1,4");
    this.add(tfMandatory, "2,4");
    this.add(cbxMandatory, "2,4");
    this.add(lovMandatory, "2,4");
    this.add(dateMandatory, "2,4");
    this.add(cbMandatoryValue, "2,4");

    this.add(lbAttributeGroup, "0,5");
    this.add(cbxAttributeGroup, "1,5 , 2,5");
    this.add(lbCalcFunction, "0,6");
    this.add(cbxCalcFunction, "1,6 , 2,6");
    this.add(lbCalculationScript, "0,7");
    this.add(btCalculationScript, "1,7");

    this.add(optionPanel, "0,8, 2,8");

    tfLabel.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            doSomeWork();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            doSomeWork();
        }

        @Override
        public void keyPressed(KeyEvent e) {
            doSomeWork();
        }

        protected void doSomeWork() {
            blnLabelModified = true;
        }

    });

    tfLabel.setDocument(new SpecialCharacterDocument());
    tfLabel.getDocument().addDocumentListener(new DocumentListener() {

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

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

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

        protected void doSomeWork(DocumentEvent e) {
            int size = e.getDocument().getLength();
            if (size > 0) {
                NuclosEntityAttributeCommonPropertiesStep.this.setComplete(true);
            } else {
                NuclosEntityAttributeCommonPropertiesStep.this.setComplete(false);
            }
            try {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setInternalName(e.getDocument().getText(0, e.getDocument().getLength()));
                if (!NuclosEntityAttributeCommonPropertiesStep.this.getModel().isEditMode()) {
                    String sPrefix = Attribute.getDBPrefix(
                            NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute());
                    tfDBFieldName.setText(sPrefix + e.getDocument().getText(0, e.getDocument().getLength()));
                }

            } catch (BadLocationException ex) {
                Errors.getInstance().showExceptionDialog(NuclosEntityAttributeCommonPropertiesStep.this, ex);
            }
        }
    });

    tfDefaultValue.getDocument().addDocumentListener(new DefaultValueDocumentListener());

    tfMandatory.getDocument().addDocumentListener(new MandatoryValueDocumentListener());
    tfMandatory.setLocale(SpringLocaleDelegate.getInstance().getLocale());

    tfDBFieldName.setDocument(new LimitCharacterDocument());
    tfDBFieldName.getDocument().addDocumentListener(new DocumentListener() {

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

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

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

        protected void doSomeWork(DocumentEvent e) {
            try {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setDbName(e.getDocument().getText(0, e.getDocument().getLength()));

                String s = e.getDocument().getText(0, e.getDocument().getLength());
                if (getModel().getAttribute().getMetaVO() != null
                        && getModel().getAttribute().getField() != null) {
                    s = "STRVALUE_" + s;
                } else if (getModel().getAttribute().getMetaVO() != null
                        && getModel().getAttribute().getField() == null) {
                    s = "INTID_" + s;
                }
                tfDBFieldNameComplete.setText(s);

            } catch (BadLocationException ex) {
                Errors.getInstance().showExceptionDialog(NuclosEntityAttributeCommonPropertiesStep.this, ex);
            }
        }
    });

    cbDistinct.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            final JCheckBox cb = (JCheckBox) e.getItem();
            NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                    .setDistinct(cb.isSelected());
            if (!cb.isSelected()) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        cbMandatory.setEnabled(true);
                    }
                });
            }
        }
    });

    cbLogBook.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            JCheckBox cb = (JCheckBox) e.getItem();
            NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                    .setLogBook(cb.isSelected());
        }
    });

    cbMandatory.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            final JCheckBox cb = (JCheckBox) e.getItem();
            NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                    .setMandatory(cb.isSelected());
            if (NuclosEntityAttributeCommonPropertiesStep.this.parentWizardModel.isEditMode() && cb.isSelected()
                    && !parentWizardModel.isVirtual()) {
                if (NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .getMandatoryValue() == null) {
                    (new Bubble(cb,
                            SpringLocaleDelegate.getInstance().getMessage(
                                    "wizard.step.attributeproperties.tooltip.28",
                                    "Bitte tragen Sie einen Wert ein mit dem das Feld vorbelegt werden kann!"),
                            3, Position.UPPER)).setVisible(true);
                }

            }
        }
    });

    cbIndexed.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            JCheckBox cb = (JCheckBox) e.getItem();
            NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                    .setIndexed(cb.isSelected());
        }
    });

    cbxDefaultValue.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                getModel().getAttribute().setIdDefaultValue((DefaultValue) e.getItem());
            }
        }
    });

    cbxMandatory.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                getModel().getAttribute().setMandatoryValue(((DefaultValue) e.getItem()).getId());
            }
        }
    });

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

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

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

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

        protected void doSomeWork(DocumentEvent e) {
            try {
                String value = e.getDocument().getText(0, e.getDocument().getLength());
                if ("Heute".equalsIgnoreCase(value)) {
                    value = RelativeDate.today().toString();
                }
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute().setDefaultValue(value);
            } catch (BadLocationException ex) {
                Errors.getInstance().showExceptionDialog(NuclosEntityAttributeCommonPropertiesStep.this, ex);
            }
        }

    });

    cbDefaultValue.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            JCheckBox cb = (JCheckBox) e.getItem();
            if (cb.isSelected()) {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute().setDefaultValue("ja");
            } else {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setDefaultValue("nein");
            }
        }
    });

    cbMandatoryValue.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            JCheckBox cb = (JCheckBox) e.getItem();
            if (cb.isSelected()) {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setMandatoryValue(Boolean.TRUE);
            } else {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setMandatoryValue(Boolean.FALSE);
            }
        }
    });

    cbxAttributeGroup.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setAttributeGroup((String) e.getItem());
                NuclosEntityAttributeCommonPropertiesStep.this.setComplete(true);
            }
        }
    });

    cbxCalcFunction.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                NuclosEntityAttributeCommonPropertiesStep.this.getModel().getAttribute()
                        .setCalcFunction((String) e.getItem());
            }
        }
    });

}

From source file:org.nuclos.client.wizard.steps.NuclosEntityAttributeValueListShipStep.java

@Override
protected void initComponents() {

    lstValues = new ArrayList<ValueList>();

    this.setLayout(new BorderLayout(5, 5));
    pnlName = new JPanel();
    pnlName.setLayout(new BorderLayout(5, 5));

    lbName = new JLabel(
            SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributevaluelist.7", "Name"));
    tfName = new JTextField();

    tfName.setDocument(new LimitSpecialCharacterDocument(25));

    pnlName.add(lbName, BorderLayout.WEST);
    pnlName.add(tfName, BorderLayout.CENTER);

    lbInfo = new JLabel(SpringLocaleDelegate.getInstance().getMessage("wizard.step.attributevaluelist.1",
            "Entitt ist schon vorhanden. Bitte anderen Namen vergeben!"));
    lbInfo.setForeground(Color.RED);
    lbInfo.setVisible(false);/*from w ww  .  ja v a 2s .c o m*/

    this.add(pnlName, BorderLayout.NORTH);
    this.add(subform, BorderLayout.CENTER);
    this.add(lbInfo, BorderLayout.SOUTH);
    subform.getSubformTable().setModel(new ValuelistTableModel());

    JTextField textField = new JTextField();
    textField.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());
    DefaultCellEditor editor = new DefaultCellEditor(textField);
    editor.setClickCountToStart(1);
    subform.getSubformTable().setDefaultEditor(String.class, editor);
    subform.getSubformTable().setDefaultEditor(Date.class, new DateEditor());

    ListenerUtil.registerSubFormToolListener(subform, this, new SubForm.SubFormToolListener() {
        @Override
        public void toolbarAction(String actionCommand) {
            if (SubForm.ToolbarFunction.fromCommandString(actionCommand) == SubForm.ToolbarFunction.NEW) {
                ValuelistTableModel model = (ValuelistTableModel) subform.getSubformTable().getModel();
                lstValues.add(new ValueList());
                model.fireTableDataChanged();
            }
        }
    });

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

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

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

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

        private void doSomeWork(DocumentEvent e) {
            try {
                String s = e.getDocument().getText(0, e.getDocument().getLength());

                model.getAttribute().setValueListName(s);
                if (s.length() == 0)
                    NuclosEntityAttributeValueListShipStep.this.setComplete(false);
                else
                    NuclosEntityAttributeValueListShipStep.this.setComplete(true);

                if (model.getAttribute().isValueListNew()) {
                    for (EntityMetaDataVO voEntity : MetaDataClientProvider.getInstance().getAllEntities()) {
                        if (s.equals(voEntity.getEntity())
                                || ("V_EO_" + s).equalsIgnoreCase(voEntity.getDbEntity())) {
                            NuclosEntityAttributeValueListShipStep.this.setComplete(false);
                            lbInfo.setVisible(true);
                            break;
                        }
                        NuclosEntityAttributeValueListShipStep.this.setComplete(true);
                        lbInfo.setVisible(false);
                    }
                }
            } catch (BadLocationException e1) {
                LOG.info("doSomeWork failed: " + e1, e1);
            }
        }
    });

}

From source file:org.nuclos.client.wizard.steps.NuclosEntityNameStep.java

@Override
protected void initComponents() {

    colMasterdata = MetaDataClientProvider.getInstance().getAllEntities();

    double size[][] = { { TableLayout.PREFERRED, 200, TableLayout.FILL },
            { 20, 20, 20, 20, 20, TableLayout.FILL } };

    TableLayout layout = new TableLayout(size);
    layout.setVGap(3);//from w  w  w. j  a  v  a 2s.c  o  m
    layout.setHGap(5);
    this.setLayout(layout);
    lbName = new JLabel(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.1",
            "Bitte geben Sie den Namen der neuen Entit\u00e4t ein") + ": ");
    tfName = new JTextField();
    tfName.setToolTipText(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.tooltip.1",
            "Namen der neuen Entit\u00e4t"));
    tfName.addFocusListener(NuclosWizardUtils.createWizardFocusAdapter());
    lbChoice = new JLabel(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.2",
            "oder w\u00e4hlen Sie eine Entit\u00e4t die Sie ver\u00e4ndern m\u00f6chten") + ": ");
    cmbEntity = new JComboBox();
    cmbEntity.setToolTipText(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.tooltip.2",
            "Namen der Entit\u00e4t die Sie ver\u00e4ndern m\u00f6chten"));
    this.fillEntityCombobox();
    cmbEntity.setEditable(true);
    AutoCompleteDecorator.decorate(cmbEntity);

    lbInfo = new JLabel();
    lbInfo.setVisible(false);
    lbInfo.setForeground(Color.RED);

    btnRemove = new JButton(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.8",
            "Entit\u00e4t entfernen"));
    btnRemove.setVisible(false);

    this.add(lbName, "0,0");
    this.add(tfName, "1,0");
    this.add(lbChoice, "0,1");
    this.add(cmbEntity, "1,1");
    this.add(lbInfo, "0,2,1,2");
    this.add(btnRemove, "0,3");

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

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

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

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

        protected void doSomeWork(DocumentEvent e) {
            int size = e.getDocument().getLength();
            try {
                for (EntityMetaDataVO metaVO : colMasterdata) {
                    if (e.getDocument().getLength() == 0) {
                        lbInfo.setVisible(false);
                        break;
                    }
                    if (e.getDocument().getLength() > 250) {
                        lbInfo.setText(SpringLocaleDelegate.getInstance().getMessage(
                                "wizard.step.entityname.12", "Der Name ist zu lang. Bitte k\u00fcrzen!"));
                        lbInfo.setVisible(true);
                        NuclosEntityNameStep.this.setComplete(false);
                        return;
                    }

                    if (e.getDocument().getText(0, size).equals(metaVO.getEntity())
                            || e.getDocument().getText(0, size).equals(SpringLocaleDelegate.getInstance()
                                    .getResource(metaVO.getLocaleResourceIdForLabel(), ""))) {
                        NuclosEntityNameStep.this.setComplete(false);
                        lbInfo.setText(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.4",
                                "Entit\u00e4t ist schon vorhanden"));
                        lbInfo.setVisible(true);
                        return;
                    } else {
                        lbInfo.setVisible(false);
                    }
                    if (e.getDocument().getLength() > 25) {
                        lbInfo.setText(
                                SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.13",
                                        "Der Tabellenname wird fr interne Zwecke gekrzt!"));
                        lbInfo.setVisible(true);
                    } else {
                        lbInfo.setVisible(false);
                    }
                }
                if (size > 0) {
                    if (cmbEntity.getSelectedIndex() > 0) {
                        NuclosEntityNameStep.this.model.resetModel();
                    }
                    NuclosEntityNameStep.this.setComplete(true);
                    cmbEntity.setSelectedIndex(0);
                    cmbEntity.setEnabled(false);
                } else {
                    //NuclosEntityNameStep.this.model.resetModel();
                    NuclosEntityNameStep.this.setComplete(false);
                    model.setTableOrViewName(null);
                    cmbEntity.setEnabled(true);
                }

                NuclosEntityNameStep.this.model
                        .setEntityName(e.getDocument().getText(0, e.getDocument().getLength()));
                if (!NuclosEntityNameStep.this.model.isEditMode()) {
                    NuclosEntityNameStep.this.model
                            .setLabelSingular(e.getDocument().getText(0, e.getDocument().getLength()));
                }
            } catch (BadLocationException ex) {
                Errors.getInstance().showExceptionDialog(NuclosEntityNameStep.this, ex);
            }
        }
    });

    cmbEntity.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(final ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                final Object obj = e.getItem();
                if (obj instanceof EntityWrapper) {
                    EntityMetaDataVO vo = ((EntityWrapper) obj).getWrappedEntity();
                    NuclosEntityNameStep.this.model.setEditMode(true);
                    NuclosEntityNameStep.this.model.resetModel();
                    NuclosEntityNameStep.this.setComplete(true);
                    btnRemove.setVisible(true);
                } else if (obj instanceof String) {
                    NuclosEntityNameStep.this.model.setEditMode(false);
                    NuclosEntityNameStep.this.model.resetModel();
                    tfName.setEnabled(true);
                    btnRemove.setVisible(false);
                    NuclosEntityNameStep.this.setComplete(false);
                }
            }
        }
    });
    ListenerUtil.registerActionListener(btnRemove, this, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                StringBuffer sbMessage = new StringBuffer();
                if (!dropEntityAllowed(((EntityWrapper) cmbEntity.getSelectedItem()).getWrappedEntity(),
                        sbMessage)) {
                    JOptionPane.showMessageDialog(
                            NuclosEntityNameStep.this, sbMessage, SpringLocaleDelegate.getInstance()
                                    .getMessage("wizard.step.inputattribute.12", "Entfernen nicht mglich!"),
                            JOptionPane.OK_OPTION);
                    return;
                }

                boolean blnImportStructure = MetaDataDelegate.getInstance().hasEntityImportStructure(
                        ((EntityWrapper) cmbEntity.getSelectedItem()).getWrappedEntity().getId());
                if (blnImportStructure) {
                    String sMessage = SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.14",
                            "Diese Entitt besitzt Strukturdefinitionen fr Objektimporte. Diese wird gelscht! Sie knnen den Vorgang abbrechen!");
                    int abort = JOptionPane
                            .showConfirmDialog(
                                    NuclosEntityNameStep.this, sMessage, SpringLocaleDelegate.getInstance()
                                            .getMessage("wizard.step.entityname.16", "Achtung!"),
                                    JOptionPane.OK_CANCEL_OPTION);
                    if (abort != JOptionPane.OK_OPTION)
                        return;
                }

                boolean blnWorkflow = MetaDataDelegate.getInstance().hasEntityWorkflow(
                        ((EntityWrapper) cmbEntity.getSelectedItem()).getWrappedEntity().getId());
                if (blnWorkflow) {
                    String sMessage = SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.15",
                            "Diese Entitt ist in einem Arbeitsschritt integriert! Dieser wird gelscht!");
                    int abort = JOptionPane
                            .showConfirmDialog(
                                    NuclosEntityNameStep.this, sMessage, SpringLocaleDelegate.getInstance()
                                            .getMessage("wizard.step.entityname.16", "Achtung!"),
                                    JOptionPane.OK_CANCEL_OPTION);
                    if (abort != JOptionPane.OK_OPTION)
                        return;
                }

                final String sMessage = SpringLocaleDelegate.getInstance().getMessage(
                        "wizard.step.entityname.9",
                        "Sind Sie sicher, dass Sie die Entit\u00e4t l\u00f6schen m\u00f6chten?");
                final String sTitle = SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.10",
                        "L\u00f6schen");

                int dropEntity = JOptionPane.showConfirmDialog(NuclosEntityNameStep.this, sMessage, sTitle,
                        JOptionPane.YES_NO_OPTION);
                switch (dropEntity) {
                case JOptionPane.YES_OPTION:
                    boolean bDropLayout = false;
                    if (MetaDataDelegate.getInstance().hasEntityLayout(
                            ((EntityWrapper) cmbEntity.getSelectedItem()).getWrappedEntity().getId())) {
                        int dropLayout = JOptionPane.showConfirmDialog(NuclosEntityNameStep.this,
                                SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.11",
                                        "Soll das Layout der Entitt gelscht werden?"),
                                sTitle, JOptionPane.YES_NO_OPTION);
                        bDropLayout = (dropLayout == JOptionPane.YES_OPTION);
                    }

                    final boolean bDropLayoutfinal = bDropLayout;
                    UIUtils.runCommandLater(getParent(), new Runnable() {

                        @Override
                        public void run() {
                            try {
                                MetaDataDelegate.getInstance().removeEntity(
                                        ((EntityWrapper) cmbEntity.getSelectedItem()).getWrappedEntity(),
                                        bDropLayoutfinal);
                                NuclosWizardUtils.flushCaches();
                                NuclosConsole.getInstance().invalidateAllCaches();
                                NuclosEntityNameStep.this.model.cancelWizard();
                            } catch (Exception ex) {
                                Errors.getInstance().showExceptionDialog(NuclosEntityNameStep.this, ex);
                                return;
                            } finally {
                                MasterDataDelegate.getInstance().invalidateLayoutCache();
                            }
                        }
                    });
                    break;
                case JOptionPane.NO_OPTION:
                default:
                    return;
                }
            } catch (Exception ex) {
                Errors.getInstance().showExceptionDialog(NuclosEntityNameStep.this, ex);
                return;
            }
        }
    });

}

From source file:org.openconcerto.erp.core.sales.credit.component.AvoirClientSQLComponent.java

private JPanel getBottomPanel() {

    // UI//w ww  . jav a  2  s  .  co m

    final JPanel panel = new JPanel(new GridBagLayout());
    panel.setOpaque(false);
    final GridBagConstraints c = new DefaultGridBagConstraints();
    c.anchor = GridBagConstraints.NORTHWEST;
    c.weightx = 1;
    // Colonne 1
    this.boxAdeduire.setOpaque(false);
    this.boxAdeduire.setMinimumSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
    this.boxAdeduire.setPreferredSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
    panel.add(this.boxAdeduire, c);
    this.addView("ID_MODE_REGLEMENT", DEC + ";" + SEP);
    this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");

    c.gridy++;
    c.fill = GridBagConstraints.NONE;
    c.weighty = 1;
    this.eltModeRegl.setOpaque(false);
    panel.add(this.eltModeRegl, c);

    // Colonne 2 : port et remise

    final JPanel panelPortEtRemise = new JPanel();
    panelPortEtRemise.setOpaque(false);
    panelPortEtRemise.setLayout(new GridBagLayout());

    final GridBagConstraints cFrais = new DefaultGridBagConstraints();

    DeviseField textPortHT = new DeviseField(5);
    DeviseField textRemiseHT = new DeviseField(5);

    // Frais de port
    cFrais.gridheight = 1;
    cFrais.fill = GridBagConstraints.VERTICAL;
    cFrais.weighty = 1;
    cFrais.gridx = 1;

    // FIXME implmenter la remise et les port pour les avoirs
    JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
    labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
    cFrais.gridy++;
    // panelPortEtRemise.add(labelPortHT, cFrais);
    cFrais.gridx++;
    DefaultGridBagConstraints.lockMinimumSize(textPortHT);
    // panelPortEtRemise.add(textPortHT, cFrais);

    // Remise
    JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
    labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
    cFrais.gridy++;
    cFrais.gridx = 1;
    // panelPortEtRemise.add(labelRemiseHT, cFrais);
    cFrais.gridx++;
    DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
    // panelPortEtRemise.add(textRemiseHT, cFrais);
    cFrais.gridy++;

    c.gridx++;
    c.gridy = 0;
    c.gridheight = 2;
    c.weightx = 0;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.NORTHWEST;
    panel.add(panelPortEtRemise, c);

    // Colonne 3 : totaux
    final DeviseField fieldHT = new DeviseField();
    final DeviseField fieldTVA = new DeviseField();
    final DeviseField fieldService = new DeviseField();
    final DeviseField fieldTTC = new DeviseField();
    // SQL
    addSQLObject(textPortHT, "PORT_HT");
    final DeviseField fieldDevise = new DeviseField();
    if (getTable().getFieldsName().contains("T_DEVISE"))
        addSQLObject(fieldDevise, "T_DEVISE");
    addSQLObject(textRemiseHT, "REMISE_HT");
    addRequiredSQLObject(fieldHT, "MONTANT_HT");
    addRequiredSQLObject(fieldTVA, "MONTANT_TVA");
    addRequiredSQLObject(fieldTTC, "MONTANT_TTC");
    addRequiredSQLObject(fieldService, "MONTANT_SERVICE");
    //
    JTextField poids = new JTextField();
    if (getTable().getFieldsName().contains("T_POIDS"))
        addSQLObject(poids, "T_POIDS");
    final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT,
            textRemiseHT, fieldService, null, fieldDevise, poids, null);
    totalTTC.setOpaque(false);
    c.gridx++;
    c.gridy = 0;
    c.gridheight = 2;
    c.fill = GridBagConstraints.BOTH;
    panel.add(totalTTC, c);

    // Listeners
    textPortHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });

    textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });
    return panel;
}

From source file:org.openconcerto.erp.core.sales.order.component.CommandeClientSQLComponent.java

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

    // Numero du commande
    c.gridx = 0;/* w ww .j  a  va 2  s. co  m*/
    this.add(new JLabel(getLabelFor("NUMERO"), SwingConstants.RIGHT), c);

    this.numeroUniqueCommande = new JUniqueTextField(16);
    c.fill = GridBagConstraints.NONE;
    c.gridx++;
    c.weightx = 1;
    this.add(this.numeroUniqueCommande, c);

    // Date
    JLabel labelDate = new JLabel(getLabelFor("DATE"));
    labelDate.setHorizontalAlignment(SwingConstants.RIGHT);
    c.gridx = 2;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    this.add(labelDate, c);

    JDate dateCommande = new JDate(true);
    c.gridx++;
    c.fill = GridBagConstraints.NONE;
    this.add(dateCommande, c);

    // Champ Module
    c.gridx = 0;
    c.gridy++;
    c.gridwidth = GridBagConstraints.REMAINDER;
    final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();

    this.setAdditionalFieldsPanel(new FormLayouter(addP, 2));
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    this.add(addP, c);

    c.gridy++;
    c.gridwidth = 1;

    this.comboDevis = new ElementComboBox();

    // Reference
    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel labelObjet = new JLabel(getLabelFor("NOM"));
    labelObjet.setHorizontalAlignment(SwingConstants.RIGHT);
    c.weightx = 0;
    this.add(labelObjet, c);

    c.gridx++;
    c.weightx = 1;
    c.fill = GridBagConstraints.BOTH;
    this.add(this.textObjet, c);

    String field;
    field = "ID_COMMERCIAL";
    c.fill = GridBagConstraints.HORIZONTAL;
    // Commercial
    JLabel labelCommercial = new JLabel(getLabelFor(field));
    labelCommercial.setHorizontalAlignment(SwingConstants.RIGHT);

    c.gridx++;
    c.weightx = 0;
    this.add(labelCommercial, c);

    this.comboCommercial = new ElementComboBox(false, 25);
    this.comboCommercial.setListIconVisible(false);
    c.gridx++;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 1;
    this.add(this.comboCommercial, c);
    addRequiredSQLObject(this.comboCommercial, field);

    // Ligne 3: Client
    c.gridx = 0;
    c.gridy++;
    c.weightx = 0;
    c.fill = GridBagConstraints.HORIZONTAL;
    this.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), c);

    this.comboClient = new ElementComboBox();
    c.gridx = GridBagConstraints.RELATIVE;
    c.gridwidth = 3;
    c.weightx = 1;
    c.weighty = 0;
    c.fill = GridBagConstraints.NONE;
    this.add(this.comboClient, c);
    final ElementComboBox boxTarif = new ElementComboBox();
    this.comboClient.addValueListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (!isFilling() && comboClient.getValue() != null) {
                Integer id = comboClient.getValue();

                if (id > 1) {

                    SQLRow row = comboClient.getElement().getTable().getRow(id);
                    if (comboClient.getElement().getTable().getFieldsName().contains("ID_TARIF")) {

                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
                        if (!foreignRow.isUndefined()
                                && (boxTarif.getSelectedRow() == null
                                        || boxTarif.getSelectedId() != foreignRow.getID())
                                && JOptionPane.showConfirmDialog(null,
                                        "Appliquer les tarifs associs au client?") == JOptionPane.YES_OPTION) {
                            boxTarif.setValue(foreignRow.getID());
                            // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
                            // true);
                        } else {
                            boxTarif.setValue(foreignRow.getID());
                        }
                        // SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
                        // if (foreignRow.isUndefined() &&
                        // !row.getForeignRow("ID_DEVISE").isUndefined()) {
                        // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
                        // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
                        // foreignRow = rowValsD;
                        //
                        // }
                        // table.setTarif(foreignRow, true);
                    }
                }
            }

        }
    });
    // tarif
    if (this.getTable().getFieldsName().contains("ID_TARIF")) {
        // TARIF
        c.gridy++;
        c.gridx = 0;
        c.weightx = 0;
        c.weighty = 0;
        c.gridwidth = 1;
        this.add(new JLabel("Tarif  appliquer"), c);
        c.gridx++;
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.weightx = 1;
        this.add(boxTarif, c);
        this.addView(boxTarif, "ID_TARIF");
        boxTarif.addModelListener("wantedID", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                SQLRow selectedRow = boxTarif.getRequest().getPrimaryTable().getRow(boxTarif.getWantedID());
                table.setTarif(selectedRow, false);
            }
        });
    }

    // Table d'lment
    this.table = new CommandeClientItemTable();
    c.fill = GridBagConstraints.BOTH;
    c.gridy++;
    c.gridx = 0;
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = GridBagConstraints.REMAINDER;
    this.add(this.table, c);

    DeviseField textPortHT = new DeviseField();
    DeviseField textRemiseHT = new DeviseField();

    // INfos
    c.gridx = 0;
    c.gridy++;
    c.gridheight = 1;
    c.weighty = 0;
    c.weightx = 1;
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 2;
    this.add(new TitledSeparator(getLabelFor("INFOS")), c);

    c.gridy++;
    c.weightx = 1;
    c.weighty = 0;
    c.fill = GridBagConstraints.BOTH;
    final JScrollPane scrollPane = new JScrollPane(this.infos);
    scrollPane.setBorder(null);
    this.add(scrollPane, c);

    // Poids
    c.gridwidth = 1;

    DefaultProps props = DefaultNXProps.getInstance();
    Boolean b = props.getBooleanValue("ArticleShowPoids");
    final JTextField textPoidsTotal = new JTextField(8);
    if (b) {
        JPanel panel = new JPanel();

        panel.add(new JLabel(getLabelFor("T_POIDS")), c);

        textPoidsTotal.setEnabled(false);
        textPoidsTotal.setHorizontalAlignment(JTextField.RIGHT);
        textPoidsTotal.setDisabledTextColor(Color.BLACK);
        panel.add(textPoidsTotal, c);

        panel.setOpaque(false);
        DefaultGridBagConstraints.lockMinimumSize(panel);

        c.gridx = 2;
        c.weightx = 0;
        c.weighty = 0;
        c.gridwidth = 1;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.NORTHEAST;
        this.add(panel, c);
    }

    // Total
    DeviseField fieldHT = new DeviseField();
    DeviseField fieldTVA = new DeviseField();
    DeviseField fieldTTC = new DeviseField();
    DeviseField fieldDevise = new DeviseField();
    DeviseField fieldService = new DeviseField();
    DeviseField fieldHA = new DeviseField();
    fieldHT.setOpaque(false);
    fieldHA.setOpaque(false);
    fieldTVA.setOpaque(false);
    fieldTTC.setOpaque(false);
    fieldService.setOpaque(false);
    addSQLObject(fieldDevise, "T_DEVISE");
    addRequiredSQLObject(fieldHT, "T_HT");
    addRequiredSQLObject(fieldTVA, "T_TVA");
    addRequiredSQLObject(fieldTTC, "T_TTC");
    addRequiredSQLObject(fieldService, "T_SERVICE");
    if (getTable().contains("PREBILAN")) {
        addSQLObject(fieldHA, "PREBILAN");
    } else if (getTable().contains("T_HA")) {
        addSQLObject(fieldHA, "T_HA");
    }

    JTextField poids = new JTextField();
    // addSQLObject(poids, "T_POIDS");
    final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT,
            textRemiseHT, fieldService, fieldHA, fieldDevise, poids, null);

    c.gridx = GridBagConstraints.RELATIVE;
    c.gridy--;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.gridheight = 2;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.fill = GridBagConstraints.NONE;
    c.weighty = 0;

    this.add(totalTTC, c);

    this.panelOO = new PanelOOSQLComponent(this);
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.EAST;
    c.gridx = 0;
    c.gridy += 3;
    c.weightx = 0;
    c.gridwidth = GridBagConstraints.REMAINDER;
    this.add(this.panelOO, c);

    textPortHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });

    textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });

    addRequiredSQLObject(this.comboClient, "ID_CLIENT");
    addSQLObject(this.textObjet, "NOM");
    addSQLObject(textPoidsTotal, "T_POIDS");
    addRequiredSQLObject(dateCommande, "DATE");
    // addRequiredSQLObject(radioEtat, "ID_ETAT_DEVIS");
    addRequiredSQLObject(this.numeroUniqueCommande, "NUMERO");
    addSQLObject(this.infos, "INFOS");
    addSQLObject(this.comboDevis, "ID_DEVIS");

    this.numeroUniqueCommande
            .setText(NumerotationAutoSQLElement.getNextNumero(CommandeClientSQLElement.class, new Date()));

    this.table.getModel().addTableModelListener(new TableModelListener() {

        public void tableChanged(TableModelEvent e) {
            textPoidsTotal.setText(String.valueOf(CommandeClientSQLComponent.this.table.getPoidsTotal()));
        }
    });
    DefaultGridBagConstraints.lockMinimumSize(comboClient);
    DefaultGridBagConstraints.lockMinimumSize(comboCommercial);
    DefaultGridBagConstraints.lockMinimumSize(comboDevis);
    DefaultGridBagConstraints.lockMinimumSize(totalTTC);
    DefaultGridBagConstraints.lockMaximumSize(totalTTC);
    DefaultGridBagConstraints.lockMinimumSize(numeroUniqueCommande);

}

From source file:org.openconcerto.erp.core.sales.pos.element.SaisieVenteComptoirSQLElement.java

public SQLComponent createComponent() {
    return new BaseSQLComponent(this) {
        private final JCheckBox checkService = new JCheckBox("dont ");
        private SQLSearchableTextCombo textNom;
        private DeviseField textMontantTTC;
        private DeviseField textMontantService;
        private ElementComboBox comboFournisseur;
        private JTextField textEcheance;

        private ElementComboBox comboTaxe;
        private DeviseField textMontantHT;
        private JCheckBox checkCommande;
        private JDate dateSaisie;

        private ElementComboBox nomArticle;
        private Date dateEch;
        private JLabel labelEcheancejours = new JLabel("jours");
        private ElementComboBox comboAvoir;
        private ElementComboBox comboClient;

        private final JLabel labelWarning = new JLabelWarning(
                "le montant du service ne peut pas dpasser le total HT!");
        private ValidState validState = ValidState.getTrueInstance();
        // FIXME: use w
        private Where w;
        private DocumentListener docTTCListen;
        private PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt) {

                if ((nomArticle.getValidState().isValid()) && (!nomArticle.isEmpty()) && !isFilling()) {
                    int idArticle = nomArticle.getValue().intValue();

                    SQLTable tableArticle = ((ComptaPropsConfiguration) Configuration.getInstance())
                            .getRootSociete().getTable("ARTICLE");
                    SQLRow rowArticle = tableArticle.getRow(idArticle);
                    if (rowArticle != null) {
                        comboTaxe.setValue(rowArticle.getInt("ID_TAXE"));

                        textMontantTTC.setText(((BigDecimal) rowArticle.getObject("PV_TTC")).toString());
                    }/*w w  w . j a va  2s.c om*/
                    System.out.println("value article Changed");

                }
            }
        };

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

            this.docTTCListen = new DocumentListener() {
                public void changedUpdate(DocumentEvent e) {
                    calculMontant();
                }

                public void removeUpdate(DocumentEvent e) {
                    calculMontant();
                }

                public void insertUpdate(DocumentEvent e) {
                    calculMontant();
                }
            };

            /***********************************************************************************
             * * RENSEIGNEMENTS
             **********************************************************************************/
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.gridheight = 1;
            TitledSeparator sep = new TitledSeparator("Renseignements");
            this.add(sep, c);
            c.insets = new Insets(2, 2, 1, 2);

            c.gridwidth = 1;

            // Libell vente
            JLabel labelNom = new JLabel(getLabelFor("NOM"));
            labelNom.setHorizontalAlignment(SwingConstants.RIGHT);
            c.gridy++;
            c.gridx = 0;
            c.weightx = 0;
            this.add(labelNom, c);

            this.textNom = new SQLSearchableTextCombo();
            c.gridx++;
            c.weightx = 1;
            c.gridwidth = 2;
            this.add(this.textNom, c);

            // Date
            JLabel labelDate = new JLabel(getLabelFor("DATE"));

            this.dateSaisie = new JDate(true);
            c.gridwidth = 1;
            // c.gridx += 2;
            c.gridx = 0;
            c.gridy++;
            c.weightx = 0;
            labelDate.setHorizontalAlignment(SwingConstants.RIGHT);
            this.add(labelDate, c);
            c.gridx++;
            c.weightx = 1;
            this.add(this.dateSaisie, c);

            // article
            c.gridy++;
            c.gridx = 0;

            this.nomArticle = new ElementComboBox();

            JLabel labelNomArticle = new JLabel(getLabelFor("ID_ARTICLE"));
            c.weightx = 0;
            labelNomArticle.setHorizontalAlignment(SwingConstants.RIGHT);
            // this.add(labelNomArticle, c);

            c.gridx++;
            c.weightx = 0;
            c.gridwidth = GridBagConstraints.REMAINDER;
            // this.add(this.nomArticle, c);

            this.nomArticle.addValueListener(this.propertyChangeListener);

            // client
            this.comboClient = new ElementComboBox();
            this.comboClient.addValueListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {

                    if (comboClient.isEmpty()) {
                        w = new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=",
                                -1);
                    } else {
                        w = new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=",
                                comboClient.getSelectedId());
                    }
                }
            });

            JLabel labelNomClient = new JLabel(getLabelFor("ID_CLIENT"));
            c.gridy++;
            c.gridx = 0;
            c.gridwidth = 1;
            c.weightx = 0;
            labelNomClient.setHorizontalAlignment(SwingConstants.RIGHT);
            this.add(labelNomClient, c);

            c.gridx++;
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.weightx = 0;
            this.add(this.comboClient, c);

            // Selection d'un avoir si le client en possede

            this.comboAvoir = new ElementComboBox();

            JLabel labelAvoirClient = new JLabel(getLabelFor("ID_AVOIR_CLIENT"));
            c.gridy++;
            c.gridx = 0;
            c.gridwidth = 1;
            c.weightx = 0;
            labelAvoirClient.setHorizontalAlignment(SwingConstants.RIGHT);
            // this.add(labelAvoirClient, c);

            c.gridx++;
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.weightx = 0;
            // this.add(this.comboAvoir, c);

            /***********************************************************************************
             * * MONTANT
             **********************************************************************************/
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.gridx = 0;
            c.gridy++;
            c.weightx = 1;
            sep = new TitledSeparator("Montant en Euros");
            c.insets = new Insets(10, 2, 1, 2);
            this.add(sep, c);
            c.insets = new Insets(2, 2, 1, 2);

            c.gridwidth = 1;

            final JLabel labelMontantHT = new JLabel(getLabelFor("MONTANT_HT"));
            labelMontantHT.setHorizontalAlignment(SwingConstants.RIGHT);
            this.textMontantHT = new DeviseField();
            this.textMontantHT.setEditable(false);
            this.textMontantHT.setEnabled(false);
            this.textMontantHT.setFocusable(false);

            final JLabel labelMontantTTC = new JLabel(getLabelFor("MONTANT_TTC"));
            labelMontantTTC.setHorizontalAlignment(SwingConstants.RIGHT);
            this.textMontantTTC = new DeviseField();
            this.textMontantTTC.getDocument().addDocumentListener(this.docTTCListen);

            // Montant HT
            c.fill = GridBagConstraints.HORIZONTAL;

            c.weightx = 0;
            c.gridy++;
            c.gridx = 0;
            c.gridwidth = 1;
            this.add(labelMontantHT, c);

            c.gridx++;
            c.weightx = 1;
            this.add(this.textMontantHT, c);

            // Montant Service

            c.gridx++;

            c.weightx = 0;
            this.add(checkService, c);

            checkService.addActionListener(new ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    if (isFilling())
                        return;
                    boolean b = checkService.isSelected();
                    textMontantService.setEditable(b);
                    textMontantService.setEnabled(b);
                    textMontantService.setFocusable(b);

                    if (!b) {
                        textMontantService.setText("");
                        // montantServiceValide = true;
                    } else {
                        textMontantService.setText(textMontantHT.getText());
                    }
                };
            });

            this.textMontantService = new DeviseField();
            c.gridx++;
            c.weightx = 1;
            this.add(this.textMontantService, c);

            JLabel labelMontantService = new JLabel("de service HT");
            c.weightx = 0;
            c.gridx++;
            this.add(labelMontantService, c);

            c.gridx++;
            c.gridwidth = GridBagConstraints.REMAINDER;
            this.add(this.labelWarning, c);
            this.labelWarning.setVisible(false);

            // Choix TVA
            c.gridy++;
            c.gridx = 0;
            c.weightx = 0;
            c.gridwidth = 1;

            final JLabel labelTaxe = new JLabel(getLabelFor("ID_TAXE"));
            labelTaxe.setHorizontalAlignment(SwingUtilities.RIGHT);
            this.add(labelTaxe, c);

            c.gridx++;
            this.comboTaxe = new ElementComboBox(false);

            c.fill = GridBagConstraints.NONE;

            this.add(this.comboTaxe, c);

            c.fill = GridBagConstraints.HORIZONTAL;

            // Montant TTC
            c.gridy++;
            c.gridx = 0;
            c.weightx = 0;
            this.add(labelMontantTTC, c);

            c.gridx++;
            c.weightx = 0;
            this.add(this.textMontantTTC, c);

            /***********************************************************************************
             * * MODE DE REGLEMENT
             **********************************************************************************/
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.gridx = 0;
            c.gridy++;
            sep = new TitledSeparator("Mode de rglement");
            c.insets = new Insets(10, 2, 1, 2);
            this.add(sep, c);
            c.insets = new Insets(2, 2, 1, 2);

            c.gridx = 0;
            c.gridy++;
            c.gridwidth = GridBagConstraints.REMAINDER;
            this.addView("ID_MODE_REGLEMENT", REQ + ";" + DEC + ";" + SEP);
            ElementSQLObject eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
            this.add(eltModeRegl, c);

            /***********************************************************************************
             * * COMMANDE
             **********************************************************************************/
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.gridx = 0;
            c.gridy++;
            sep = new TitledSeparator("Commande");
            c.insets = new Insets(10, 2, 1, 2);
            this.add(sep, c);
            c.insets = new Insets(2, 2, 1, 2);

            this.checkCommande = new JCheckBox("Produit  commander");

            c.gridx = 0;
            c.gridy++;
            c.weightx = 0;
            c.gridwidth = 2;
            // this.add(this.checkCommande, c);

            this.checkCommande.addActionListener(new ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    boolean b = checkCommande.isSelected();
                    comboFournisseur.setEnabled(b);
                    comboFournisseur.setEditable(b);

                    textEcheance.setEditable(b);
                    textEcheance.setEnabled(b);

                    updateValidState();
                };
            });

            // Fournisseurs
            JLabel labelFournisseur = new JLabel(getLabelFor("ID_FOURNISSEUR"));
            c.gridx = 0;
            c.gridy++;
            c.weightx = 0;
            c.gridwidth = 1;
            labelFournisseur.setHorizontalAlignment(SwingConstants.RIGHT);
            // this.add(labelFournisseur, c);

            this.comboFournisseur = new ElementComboBox();

            c.gridx++;
            c.weightx = 1;
            c.gridwidth = 4;
            // this.add(this.comboFournisseur, c);

            // Echeance
            JLabel labelEcheance = new JLabel("Echeance");
            c.gridx = 0;
            c.gridy++;
            c.weightx = 0;
            c.gridwidth = 1;
            labelEcheance.setHorizontalAlignment(SwingConstants.RIGHT);
            // this.add(labelEcheance, c);

            c.gridx++;
            c.weightx = 1;
            this.textEcheance = new JTextField();
            // this.add(this.textEcheance, c);
            this.textEcheance.addKeyListener(new KeyAdapter() {

                public void keyReleased(KeyEvent e) {
                    calculDate();
                }
            });

            c.gridx++;
            c.weightx = 0;
            // this.add(this.labelEcheancejours, c);

            /***********************************************************************************
             * * INFORMATIONS COMPLEMENTAIRES
             **********************************************************************************/
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.gridx = 0;
            c.gridy++;
            sep = new TitledSeparator("Informations complmentaires");
            c.insets = new Insets(10, 2, 1, 2);
            // this.add(sep, c);
            c.insets = new Insets(2, 2, 1, 2);

            ITextArea textInfos = new ITextArea();

            c.gridx = 0;
            c.gridy++;
            c.gridheight = GridBagConstraints.REMAINDER;
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.weightx = 1;
            c.weighty = 1;
            c.fill = GridBagConstraints.BOTH;
            // this.add(textInfos, c);

            this.addSQLObject(this.textNom, "NOM");
            this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
            this.addSQLObject(this.nomArticle, "ID_ARTICLE");
            this.addRequiredSQLObject(this.textMontantTTC, "MONTANT_TTC");
            this.addRequiredSQLObject(this.textMontantHT, "MONTANT_HT");
            this.addSQLObject(this.textMontantService, "MONTANT_SERVICE");
            this.addRequiredSQLObject(this.dateSaisie, "DATE");
            this.addSQLObject(textInfos, "INFOS");
            this.addSQLObject(this.comboFournisseur, "ID_FOURNISSEUR");
            this.addSQLObject(this.textEcheance, "ECHEANCE");
            this.addRequiredSQLObject(this.comboTaxe, "ID_TAXE");
            this.addSQLObject(this.comboAvoir, "ID_AVOIR_CLIENT");
            this.comboTaxe.setButtonsVisible(false);
            this.comboTaxe.setValue(2);

            checkService.setSelected(false);
            this.textMontantService.setEditable(false);
            this.textMontantService.setEnabled(false);

            this.checkCommande.setSelected(false);
            this.comboFournisseur.setEditable(false);
            this.comboFournisseur.setEnabled(false);
            this.textEcheance.setEditable(false);
            this.textEcheance.setEnabled(false);

            this.comboTaxe.addValueListener(new PropertyChangeListener() {

                public void propertyChange(PropertyChangeEvent evt) {
                    calculMontant();
                }
            });

            final SimpleDocumentListener docL = new SimpleDocumentListener() {
                @Override
                public void update(DocumentEvent e) {
                    updateValidState();
                }
            };
            this.textMontantService.getDocument().addDocumentListener(docL);
            this.textMontantHT.getDocument().addDocumentListener(docL);
            this.comboFournisseur.addEmptyListener(new EmptyListener() {
                @Override
                public void emptyChange(EmptyObj src, boolean newValue) {
                    updateValidState();
                }
            });

            /*
             * this.nomClient.addValueListener(new PropertyChangeListener() {
             * 
             * public void propertyChange(PropertyChangeEvent evt) { if (nomClient.isValid()) {
             * System.err.println("Changed Combo Avoir"); comboAvoir = new ElementComboBox(new
             * AvoirClientSQLElement(new Where(new
             * AvoirClientSQLElement().getTable().getField("ID_CLIENT"), "=",
             * nomClient.getValue()))); if (comboAvoir != null) { comboAvoir.setEnabled(true); }
             * } else { comboAvoir.setEnabled(false); } } });
             */

        }

        @Override
        public Set<String> getPartialResetNames() {
            Set<String> s = new HashSet<String>();
            s.addAll(super.getPartialResetNames());
            s.add("MONTANT_TTC");
            s.add("MONTANT_SERVICE");
            s.add("MONTANT_HT");
            s.add("NOM");
            s.add("ID_AVOIR_CLIENT");
            s.add("ID_ARTICLE");
            s.add("INFOS");
            return s;
        }

        private void calculMontant() {

            if (!isFilling()) {

                float taux;
                // PrixHT pHT;
                PrixTTC pTTC;
                // taux de la TVA selectionnee
                int idTaxe = this.comboTaxe.getSelectedId();
                if (idTaxe > 1) {
                    SQLRow ligneTaxe = getTable().getBase().getTable("TAXE").getRow(idTaxe);
                    if (ligneTaxe != null) {
                        taux = (ligneTaxe.getFloat("TAUX")) / 100.0F;

                        // calcul des montants HT ou TTC
                        if (this.textMontantTTC.getText().trim().length() > 0) {

                            if (this.textMontantTTC.getText().trim().equals("-")) {
                                pTTC = new PrixTTC(0);
                            } else {
                                pTTC = new PrixTTC(
                                        GestionDevise.parseLongCurrency(this.textMontantTTC.getText()));
                            }

                            // affichage
                            updateTextHT(GestionDevise.currencyToString(pTTC.calculLongHT(taux)));
                        } else {
                            updateTextHT("");
                        }
                    }
                }
            }
        }

        private boolean isMontantServiceValid() {
            String montant = this.textMontantService.getText().trim();
            String montantHT = this.textMontantHT.getText().trim();

            boolean b;
            if (montant.length() == 0) {
                b = true;
            } else {
                if (montantHT.length() == 0) {
                    b = false;
                } else {
                    b = (GestionDevise.parseLongCurrency(montantHT) >= GestionDevise
                            .parseLongCurrency(montant));
                }
            }

            this.labelWarning.setVisible(!b);
            System.err.println("Montant service is valid ? " + b + " --> HT val " + montantHT
                    + " --> service val " + montant);

            return b;
        }

        /*
         * private void calculMontantHT() {
         * 
         * float taux; PrixHT pHT;
         * 
         * if (!this.comboTaxe.isEmpty()) { // taux de la TVA selectionnee SQLRow ligneTaxe =
         * Configuration.getInstance().getBase().getTable("TAXE").getRow(((Integer)
         * this.comboTaxe.getValue()).intValue()); taux = (ligneTaxe.getFloat("TAUX")) / 100; //
         * calcul des montants HT ou TTC if (this.textMontantHT.getText().trim().length() > 0) {
         * 
         * if (this.textMontantHT.getText().trim().equals("-")) { pHT = new PrixHT(0); } else {
         * pHT = new PrixHT(Float.parseFloat(this.textMontantHT.getText())); } // affichage
         * updateTextTTC(String.valueOf(pHT.CalculTTC(taux))); } else updateTextTTC(""); } }
         */

        private void updateTextHT(final String prixHT) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {

                    textMontantHT.setText(prixHT);
                }
            });
        }

        @Override
        protected SQLRowValues createDefaults() {
            SQLRowValues vals = new SQLRowValues(this.getTable());
            SQLRowAccessor r;

            try {
                r = ModeReglementDefautPrefPanel.getDefaultRow(true);
                SQLElement eltModeReglement = Configuration.getInstance().getDirectory()
                        .getElement("MODE_REGLEMENT");
                if (r.getID() > 1) {
                    SQLRowValues rowVals = eltModeReglement.createCopy(r.getID());
                    System.err.println(rowVals.getInt("ID_TYPE_REGLEMENT"));
                    vals.put("ID_MODE_REGLEMENT", rowVals);
                }
            } catch (SQLException e) {
                System.err.println("Impossible de slectionner le mode de rglement par dfaut du client.");
                e.printStackTrace();
            }
            return vals;
        }

        // private void updateTextTTC(final String prixTTC) {
        // SwingUtilities.invokeLater(new Runnable() {
        //
        // public void run() {
        //
        // if (docTTCListen != null) {
        //
        // textMontantTTC.getDocument().removeDocumentListener(docTTCListen);
        // }
        //
        // textMontantTTC.setText(prixTTC);
        //
        // // textTaxe.setText(prixTVA);
        // textMontantTTC.getDocument().addDocumentListener(docTTCListen);
        // }
        // });
        // }

        private void calculDate() {

            int aJ = 0;

            // on rcupre les valeurs saisies
            if (this.textEcheance.getText().trim().length() != 0) {

                try {
                    aJ = Integer.parseInt(this.textEcheance.getText());
                } catch (Exception e) {
                    System.out.println("Erreur de format sur TextField Ajour " + this.textEcheance.getText());
                }
            }

            Calendar cal = Calendar.getInstance();

            // on fixe le temps sur ToDay + Ajour
            cal.setTime(new Date());
            long tempsMil = aJ * 86400000;
            cal.setTimeInMillis(cal.getTimeInMillis() + tempsMil);

            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
            this.dateEch = cal.getTime();
            this.labelEcheancejours.setText("jours, soit le " + dateFormat.format(this.dateEch));
        }

        private void updateValidState() {
            this.setValidState(this.computeValidState());
        }

        private ValidState computeValidState() {
            ValidState res = ValidState.getTrueInstance();
            if (!this.isMontantServiceValid())
                res = res.and(ValidState.createCached(false, this.labelWarning.getText()));
            if (this.checkCommande.isSelected())
                res = res.and(ValidState.createCached(!this.comboFournisseur.isEmpty(),
                        "Fournisseur non renseign"));
            return res;
        }

        private final void setValidState(ValidState validState) {
            if (!validState.equals(this.validState)) {
                this.validState = validState;
                this.fireValidChange();
            }
        }

        @Override
        public synchronized ValidState getValidState() {
            return super.getValidState().and(this.validState);
        }

        public int insert(SQLRow order) {

            // On teste si l'article n'existe pas, on le cre
            if (this.nomArticle.isEmpty()) {
                createArticle();
            }

            if (this.textNom.getValue() == null || this.textNom.getValue().trim().length() <= 0) {
                this.textNom.setValue(this.nomArticle.getTextComp().getText());
            }
            final int id = super.insert(order);
            // on verifie si le produit est  commander
            if (this.checkCommande.isSelected()) {
                createCommande(id);
            }

            SQLRow rowArt = getTable().getRow(id).getForeignRow("ID_ARTICLE");
            if (rowArt != null && !rowArt.isUndefined() && rowArt.getBoolean("GESTION_STOCK")) {
                Configuration.getInstance().getNonInteractiveSQLExecutor().execute(new Runnable() {

                    @Override
                    public void run() {

                        final SQLRow rowVC = getTable().getRow(id);
                        // Mise  jour des stocks
                        final SQLElement eltMvtStock = Configuration.getInstance().getDirectory()
                                .getElement("MOUVEMENT_STOCK");
                        final SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
                        rowVals.put("QTE", -1);
                        rowVals.put("NOM", "Saisie vente comptoir");
                        rowVals.put("IDSOURCE", id);
                        rowVals.put("SOURCE", getTable().getName());
                        rowVals.put("ID_ARTICLE", rowVC.getInt("ID_ARTICLE"));
                        rowVals.put("DATE", rowVC.getObject("DATE"));

                        try {
                            final SQLRow row = rowVals.insert();
                            final ListMap<SQLRow, SQLRowValues> map = ((MouvementStockSQLElement) Configuration
                                    .getInstance().getDirectory().getElement("MOUVEMENT_STOCK"))
                                            .updateStock(Arrays.asList(row), false);
                            MouvementStockSQLElement.createCommandeF(map, null);

                        } catch (SQLException e) {
                            ExceptionHandler.handle("Erreur lors de la cration des mouvements de stock", e);
                        }
                    }
                });

            }
            new GenerationMvtSaisieVenteComptoir(id);
            return id;
        }

        private void createCommande(final int id) {

            System.out.println("Ajout d'une commande");
            SQLRow rowSaisie = SaisieVenteComptoirSQLElement.this.getTable().getRow(id);
            Map<String, Object> m = new HashMap<String, Object>();
            // NOM, DATE, ECHEANCE, IDSOURCE, SOURCE, ID_CLI, ID_FOURN, ID_ARTICLE
            m.put("NOM", rowSaisie.getObject("NOM"));
            m.put("DATE", rowSaisie.getObject("DATE"));
            m.put("DATE_ECHEANCE", new java.sql.Date(this.dateEch.getTime()));

            m.put("IDSOURCE", new Integer(id));
            m.put("SOURCE", "SAISIE_VENTE_COMPTOIR");

            m.put("ID_CLIENT", rowSaisie.getObject("ID_CLIENT"));
            m.put("ID_FOURNISSEUR", rowSaisie.getObject("ID_FOURNISSEUR"));
            m.put("ID_ARTICLE", rowSaisie.getObject("ID_ARTICLE"));

            SQLTable tableCmd = getTable().getBase().getTable("COMMANDE_CLIENT");

            SQLRowValues valCmd = new SQLRowValues(tableCmd, m);

            try {
                if (valCmd.getInvalid() == null) {
                    // ajout de l'ecriture
                    valCmd.insert();
                }
            } catch (Exception e) {
                System.err.println("Erreur  l'insertion dans la table " + valCmd.getTable().getName());
                e.printStackTrace();
            }
        }

        private void createArticle() {
            System.out.println("Cration de l'article");

            String tNomArticle = this.nomArticle.getTextComp().getText();
            String codeArticle = "";// this.nomArticle.getTextOpt();

            if (tNomArticle.trim().length() == 0 && codeArticle.trim().length() == 0) {
                return;
            }

            SQLTable articleTable = getTable().getBase().getTable("ARTICLE");

            int idTaxe = this.comboTaxe.getSelectedId();
            final BigDecimal prix = StringUtils.getBigDecimalFromUserText(this.textMontantHT.getText());
            final BigDecimal prixTTC = StringUtils.getBigDecimalFromUserText(this.textMontantTTC.getText());

            if (tNomArticle.trim().length() == 0) {
                tNomArticle = "Nom Indefini";
            }
            if (codeArticle.trim().length() == 0) {
                codeArticle = "Indefini";
            }

            SQLRowValues vals = new SQLRowValues(articleTable);
            vals.put("NOM", tNomArticle);
            vals.put("CODE", codeArticle);
            vals.put("PA_HT", prix);
            vals.put("PV_HT", prix);
            vals.put("PRIX_METRIQUE_VT_1", prix);
            vals.put("PRIX_METRIQUE_HA_1", prix);
            vals.put("PV_TTC", prixTTC);
            vals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
            vals.put("ID_TAXE", new Integer(idTaxe));
            vals.put("CREATION_AUTO", Boolean.TRUE);
            vals.put("GESTION_STOCK", Boolean.FALSE);

            try {
                SQLRow row = vals.insert();
                this.nomArticle.setValue(row);
            } catch (SQLException e) {

                e.printStackTrace();
            }
        }

        public void update() {

            if (JOptionPane.showConfirmDialog(this,
                    "Attention en modifiant cette vente comptoir, vous supprimerez les chques et les chances associs. Continuer?",
                    "Modification de vente comptoir", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                // on efface les mouvements de stocks associs
                SQLRow row = getTable().getRow(this.getSelectedID());
                SQLElement eltMvtStock = Configuration.getInstance().getDirectory()
                        .getElement("MOUVEMENT_STOCK");
                SQLSelect sel = new SQLSelect();
                sel.addSelect(eltMvtStock.getTable().getField("ID"));
                Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
                Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
                sel.setWhere(w.and(w2));

                List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(),
                        new ArrayListHandler());
                if (l != null) {
                    for (int i = 0; i < l.size(); i++) {
                        Object[] tmp = (Object[]) l.get(i);
                        try {
                            eltMvtStock.archive(((Number) tmp[0]).intValue());
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }

                if (this.textNom.getValue() != null && this.textNom.getValue().trim().length() <= 0) {
                    this.textNom.setValue(this.nomArticle.getTextComp().getText());
                }

                // On teste si l'article n'existe pas, on le cre
                if (this.nomArticle.getValue() == null
                        || Integer.parseInt(this.nomArticle.getValue().toString()) == -1) {
                    createArticle();
                }

                // TODO check echeance, ---> creation article, commande??
                super.update();

                row = getTable().getRow(this.getSelectedID());
                int idMvt = row.getInt("ID_MOUVEMENT");
                System.out.println(row.getID() + "__________***************** UPDATE " + idMvt);

                // on supprime tout ce qui est li  la facture
                EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory()
                        .getElement("ECRITURE");
                eltEcr.archiveMouvementProfondeur(idMvt, false);

                SQLRow rowArt = row.getForeignRow("ID_ARTICLE");
                if (rowArt != null && !rowArt.isUndefined() && rowArt.getBoolean("GESTION_STOCK")) {
                    // Mise  jour des stocks
                    SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
                    rowVals.put("QTE", -1);
                    rowVals.put("NOM", "Saisie vente comptoir");
                    rowVals.put("IDSOURCE", getSelectedID());
                    rowVals.put("SOURCE", getTable().getName());
                    rowVals.put("ID_ARTICLE", row.getInt("ID_ARTICLE"));
                    rowVals.put("DATE", row.getObject("DATE"));
                    try {
                        SQLRow rowNew = rowVals.insert();
                        final ListMap<SQLRow, SQLRowValues> map = ((MouvementStockSQLElement) Configuration
                                .getInstance().getDirectory().getElement("MOUVEMENT_STOCK"))
                                        .updateStock(Arrays.asList(rowNew), false);
                        ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor()
                                .execute(new Runnable() {

                                    @Override
                                    public void run() {
                                        MouvementStockSQLElement.createCommandeF(map, null);
                                    }
                                });
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (idMvt > 1) {
                    new GenerationMvtSaisieVenteComptoir(this.getSelectedID(), idMvt);
                } else {
                    new GenerationMvtSaisieVenteComptoir(this.getSelectedID());
                }
            }
        }

        @Override
        public void select(SQLRowAccessor r) {
            this.textMontantTTC.getDocument().removeDocumentListener(this.docTTCListen);
            this.nomArticle.rmValueListener(this.propertyChangeListener);

            super.select(r);

            checkService.setSelected(
                    r != null && r.getObject("MONTANT_SERVICE") != null && r.getLong("MONTANT_SERVICE") > 0);

            this.textMontantTTC.getDocument().addDocumentListener(this.docTTCListen);
            this.nomArticle.addValueListener(this.propertyChangeListener);
        }

        @Override
        public void select(SQLRowAccessor r, Set<String> views) {
            super.select(r, views);
            checkService.setSelected(
                    r != null && r.getObject("MONTANT_SERVICE") != null && r.getLong("MONTANT_SERVICE") > 0);
        }

    };
}

From source file:org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent.java

private JPanel getBottomPanel() {
    final JPanel panel = new JPanel(new GridBagLayout());
    final GridBagConstraints c = new DefaultGridBagConstraints();

    // Colonne 1 : Infos
    c.gridx = 0;/*from  ww  w  . j a va  2  s  .  c o m*/
    c.weightx = 1;
    c.anchor = GridBagConstraints.WEST;
    c.fill = GridBagConstraints.HORIZONTAL;

    panel.add(new TitledSeparator(getLabelFor("INFOS")), c);

    c.gridy++;
    c.weighty = 0;
    c.weightx = 1;
    c.fill = GridBagConstraints.BOTH;
    final JScrollPane scrollPane = new JScrollPane(this.infos);
    scrollPane.setBorder(null);
    panel.add(scrollPane, c);

    // Colonne 2 : Poids & autres
    DefaultProps props = DefaultNXProps.getInstance();
    Boolean b = props.getBooleanValue("ArticleShowPoids");
    final JTextField textPoidsTotal = new JTextField(8);
    JTextField poids = new JTextField();
    if (b) {
        final JPanel panelPoids = new JPanel();

        panelPoids.add(new JLabel(getLabelFor("T_POIDS")), c);

        textPoidsTotal.setEnabled(false);
        textPoidsTotal.setHorizontalAlignment(JTextField.RIGHT);
        textPoidsTotal.setDisabledTextColor(Color.BLACK);

        panelPoids.add(textPoidsTotal, c);

        c.gridx++;
        c.gridy = 0;
        c.weightx = 0;
        c.weighty = 0;
        c.gridwidth = 1;
        c.gridheight = 2;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.NORTHEAST;
        panel.add(panelPoids, c);
        DefaultGridBagConstraints.lockMinimumSize(panelPoids);
        addSQLObject(textPoidsTotal, "T_POIDS");
    } else {
        addSQLObject(poids, "T_POIDS");
    }

    DeviseField textPortHT = new DeviseField();
    ElementComboBox comboTaxePort = new ElementComboBox();

    if (getTable().contains("PORT_HT")) {
        addRequiredSQLObject(textPortHT, "PORT_HT");
        final JPanel panelPoids = new JPanel(new GridBagLayout());
        GridBagConstraints cPort = new DefaultGridBagConstraints();
        cPort.gridx = 0;
        cPort.weightx = 0;
        panelPoids.add(new JLabel(getLabelFor("PORT_HT")), cPort);
        textPortHT.setHorizontalAlignment(JTextField.RIGHT);
        cPort.gridx++;
        cPort.weightx = 1;
        panelPoids.add(textPortHT, cPort);

        cPort.gridy++;
        cPort.gridx = 0;
        cPort.weightx = 0;
        addRequiredSQLObject(comboTaxePort, "ID_TAXE_PORT");
        panelPoids.add(new JLabel(getLabelFor("ID_TAXE_PORT")), cPort);
        cPort.gridx++;
        cPort.weightx = 0;
        panelPoids.add(comboTaxePort, cPort);

        c.gridx++;
        c.gridy = 0;
        c.weightx = 0;
        c.weighty = 0;
        c.gridwidth = 1;
        c.gridheight = 2;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.NORTHEAST;
        panel.add(panelPoids, c);
        DefaultGridBagConstraints.lockMinimumSize(panelPoids);
    }
    // Total

    DeviseField textRemiseHT = new DeviseField();
    DeviseField fieldHT = new DeviseField();
    DeviseField fieldTVA = new DeviseField();
    DeviseField fieldTTC = new DeviseField();
    DeviseField fieldDevise = new DeviseField();
    DeviseField fieldService = new DeviseField();
    fieldHT.setOpaque(false);
    fieldTVA.setOpaque(false);
    fieldTTC.setOpaque(false);
    fieldService.setOpaque(false);
    addRequiredSQLObject(fieldDevise, "T_DEVISE");
    addRequiredSQLObject(fieldHT, "T_HT");
    addRequiredSQLObject(fieldTVA, "T_TVA");

    addRequiredSQLObject(fieldTTC, "T_TTC");
    addRequiredSQLObject(fieldService, "T_SERVICE");
    final TotalPanel totalTTC = new TotalPanel(this.table, fieldHT, fieldTVA, fieldTTC, textPortHT,
            textRemiseHT, fieldService, null, fieldDevise, null, null,
            (getTable().contains("ID_TAXE_PORT") ? comboTaxePort : null));

    c.gridx++;
    c.gridy--;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.gridheight = 2;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.fill = GridBagConstraints.BOTH;
    c.weighty = 0;
    DefaultGridBagConstraints.lockMinimumSize(totalTTC);

    panel.add(totalTTC, c);

    c.gridy += 3;
    c.gridheight = 2;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.EAST;
    panel.add(getModuleTotalPanel(), c);

    table.getModel().addTableModelListener(new TableModelListener() {

        public void tableChanged(TableModelEvent e) {
            textPoidsTotal.setText(String.valueOf(table.getPoidsTotal()));
        }
    });

    textPortHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });

    comboTaxePort.addValueListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            // TODO Raccord de mthode auto-gnr
            totalTTC.updateTotal();
        }
    });

    textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void removeUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }

        public void insertUpdate(DocumentEvent e) {
            totalTTC.updateTotal();
        }
    });
    return panel;
}

From source file:org.openconcerto.map.ui.ITextComboVilleViewer.java

public ITextComboVilleViewer() {
    this.setOpaque(false);
    this.setLayout(new BorderLayout());

    this.supp = new ValueChangeSupport<String>(this);
    this.emptyHelper = new EmptyObjectHelper(this, new Predicate() {
        public boolean evaluate(final Object object) {
            // object: le getUncheckedValue()
            return ITextComboVilleViewer.this.getValue() == null
                    || ITextComboVilleViewer.this.getValue().trim().length() == 0;
        }//from   w  ww  .ja  v  a 2 s .  c o m
    });
    this.text.addValueListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            ITextComboVilleViewer.this.supp.fireValueChange();
        }
    });

    this.cache = new ITextComboCacheVille();
    this.text.initCache(this.cache);
    this.add(this.text, BorderLayout.CENTER);

    this.add(this.button, BorderLayout.EAST);
    this.button.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
            final JFrame f = new JFrame();
            final MapViewerPanel mapViewerPanel = new MapViewerPanel(true);

            f.setContentPane(mapViewerPanel);
            f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            f.setSize(600, 500);
            f.setMinimumSize(new Dimension(600, 500));
            final File conf = new File(System.getProperty("user.home"),
                    ".java" + File.separator + "ilm" + File.separator + "map" + File.separator);
            new WindowStateManager(f, new File(conf, "Configuration" + File.separator + "MapFrame.properties"),
                    true).loadState();
            f.setVisible(true);
            if (ITextComboVilleViewer.this.currentVille != null) {
                final long x = ITextComboVilleViewer.this.currentVille.getXLambert();
                final long y = ITextComboVilleViewer.this.currentVille.getYLambert();
                f.setTitle(ITextComboVilleViewer.this.currentVille.getName());
                mapViewerPanel.getVilleRendererPanel().centerScreenXYLambert(x, y);
                mapViewerPanel.getVilleRendererPanel().setHighlight(ITextComboVilleViewer.this.currentVille);
                mapViewerPanel.getVilleRendererPanel().setAlwayVisible(ITextComboVilleViewer.this.currentVille);
            }
        }
    });
    this.text.getDocument().addDocumentListener(new DocumentListener() {

        public void changedUpdate(final DocumentEvent e) {
            ITextComboVilleViewer.this.currentVille = Ville
                    .getVilleFromVilleEtCode(ITextComboVilleViewer.this.text.getValue());
            ITextComboVilleViewer.this.button.setEnabled(
                    ITextComboVilleViewer.this.currentVille != null && ITextComboVilleViewer.this.isEnabled());

        }

        public void insertUpdate(final DocumentEvent e) {
            this.changedUpdate(e);
        }

        public void removeUpdate(final DocumentEvent e) {
            this.changedUpdate(e);
        }
    });
    final JPopupMenu popupMenu = new JPopupMenu();
    // FIXME ajouter la possibilit de supprimer une ville prcdemment enregistre
    final JMenuItem menuItem = new JMenuItem("Enregistrer cette ville");
    menuItem.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
            final String t = ITextComboVilleViewer.this.text.getTextComp().getText();
            ITextComboVilleViewer.this.cache.addToCache(t);
            final Ville createVilleFrom = ITextComboVilleViewer.this.cache.createVilleFrom(t);
            if (createVilleFrom != null) {
                final String villeEtCode = createVilleFrom.getVilleEtCode();
                ITextComboVilleViewer.this.setValue(villeEtCode);
                ITextComboVilleViewer.this.firePropertyChange("value", null, villeEtCode);
            }
        }
    });
    popupMenu.add(menuItem);

    this.text.getTextComp().addMouseListener(new PopupMouseListener(popupMenu));

}

From source file:org.opendatakit.appengine.updater.UpdaterWindow.java

/**
 * Create the application.//from ww  w. ja  v  a  2s.  com
 */
public UpdaterWindow(CommandLine cmd) {
    super();
    AnnotationProcessor.process(this);// if not using AOP
    this.cmd = cmd;
    frame = new JFrame();
    frame.setBounds(100, 100, isLinux() ? 720 : 680, 595);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.addWindowListener(new WindowListener() {
        @Override
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void windowClosing(WindowEvent e) {
        }

        @Override
        public void windowClosed(WindowEvent e) {
        }

        @Override
        public void windowIconified(WindowEvent e) {
        }

        @Override
        public void windowDeiconified(WindowEvent e) {
        }

        @Override
        public void windowActivated(WindowEvent e) {
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
        }
    });

    JLabel lblEmail = new JLabel(t(TranslatedStrings.EMAIL_LABEL));

    txtEmail = new JTextField();
    txtEmail.setFocusable(true);
    txtEmail.setEditable(true);
    txtEmail.setColumns(60);
    txtEmail.setMaximumSize(txtEmail.getPreferredSize());
    if (cmd.hasOption(ArgumentNameConstants.EMAIL)) {
        txtEmail.setText(cmd.getOptionValue(ArgumentNameConstants.EMAIL));
    }
    lblEmail.setLabelFor(txtEmail);

    JLabel lblToken = new JLabel(t(TranslatedStrings.TOKEN_GRANTING_LABEL));

    txtToken = new JTextField();
    txtToken.setColumns(60);
    txtToken.setMaximumSize(txtToken.getPreferredSize());
    txtToken.setFocusable(false);
    txtToken.setEditable(false);
    if (cmd.hasOption(ArgumentNameConstants.TOKEN_GRANTING_CODE)) {
        txtToken.setText(cmd.getOptionValue(ArgumentNameConstants.TOKEN_GRANTING_CODE));
    }
    lblToken.setLabelFor(txtToken);

    // set up listener for updating warning message
    txtEmail.getDocument().addDocumentListener(new DocumentListener() {

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

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

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

    });

    // set up listener for updating warning message
    txtToken.getDocument().addDocumentListener(new DocumentListener() {

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

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

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

    });

    if ((txtEmail.getText().length() > 0) && ((txtToken.getText().length() > 0) || perhapsHasToken())) {
        lblWarning = new JLabel(t(TranslatedStrings.WARNING_ERRANT_LABEL));
    } else {
        lblWarning = new JLabel(t(TranslatedStrings.WARNING_REDIRECT_LABEL));
    }

    JLabel outputArea = new JLabel(t(TranslatedStrings.OUTPUT_LBL));
    editorArea = new JTextPane(new DefaultStyledDocument());
    editorArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
    //Put the editor pane in a scroll pane.
    editorScrollPane = new JScrollPane(editorArea);
    editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    editorScrollPane.setPreferredSize(new Dimension(400, 300));
    editorScrollPane.setMinimumSize(new Dimension(10, 10));

    outputArea.setLabelFor(editorScrollPane);
    // Create a container so that we can add a title around
    // the scroll pane. Can't add a title directly to the
    // scroll pane because its background would be white.
    // Lay out the label and scroll pane from top to bottom.
    JPanel listPane = new JPanel();
    listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
    listPane.add(outputArea);
    listPane.add(Box.createRigidArea(new Dimension(0, 5)));
    listPane.add(editorScrollPane);
    listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    btnDeleteToken = new JButton(t(TranslatedStrings.DELETE_TOKEN_LABEL));
    btnDeleteToken.addActionListener(new DeleteTokenActionListener());
    btnDeleteToken.setEnabled(perhapsHasToken());

    btnChoose = new JButton(t(TranslatedStrings.GET_TOKEN_LABEL));
    if ((txtEmail.getText().length() > 0) && (txtToken.getText().length() > 0) || perhapsHasToken()) {
        if (perhapsHasToken()) {
            btnChoose.setText(t(TranslatedStrings.VERIFY_TOKEN_LABEL));
        } else {
            btnChoose.setText(t(TranslatedStrings.SET_TOKEN_LABEL));
        }
    } else {
        btnChoose.setText(t(TranslatedStrings.GET_TOKEN_LABEL));
    }
    btnChoose.addActionListener(new GetTokenActionListener());
    btnChoose.setEnabled(txtEmail.getText().length() > 0);

    btnUpload = new JButton(t(TranslatedStrings.UPLOAD_LABEL));
    btnUpload.addActionListener(new UploadActionListener());
    btnUpload.setEnabled((txtEmail.getText().length() > 0) && perhapsHasToken());

    btnRollback = new JButton(t(TranslatedStrings.ROLLBACK_LABEL));
    btnRollback.addActionListener(new RollbackActionListener());
    btnRollback.setEnabled((txtEmail.getText().length() > 0) && perhapsHasToken());

    GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
    groupLayout
            .setHorizontalGroup(
                    groupLayout.createSequentialGroup().addContainerGap()
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblEmail)
                                    .addComponent(txtEmail).addComponent(lblToken).addComponent(txtToken)
                                    .addComponent(lblWarning).addComponent(listPane)
                                    .addGroup(groupLayout.createSequentialGroup().addComponent(btnDeleteToken)
                                            .addGap(3 * HorizontalSpacing).addComponent(btnChoose)
                                            .addGap(HorizontalSpacing).addComponent(btnUpload)
                                            .addGap(3 * HorizontalSpacing, 4 * HorizontalSpacing,
                                                    Short.MAX_VALUE)
                                            .addComponent(btnRollback)))
                            .addContainerGap());

    groupLayout.setVerticalGroup(groupLayout.createSequentialGroup().addContainerGap().addComponent(lblEmail)
            .addPreferredGap(ComponentPlacement.RELATED).addComponent(txtEmail)
            .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(lblToken)
            .addPreferredGap(ComponentPlacement.RELATED).addComponent(txtToken)
            .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(lblWarning)
            .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(listPane)
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(btnDeleteToken)
                    .addComponent(btnChoose).addComponent(btnUpload).addComponent(btnRollback))
            .addContainerGap());

    frame.getContentPane().setLayout(groupLayout);

    frame.addWindowListener(this);
}

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

/** Initializes the components composing this display. */
private void initComponents() {
    admin = false;//from  ww w  .  j av  a2  s .  co m
    active = false;
    groupOwner = false;

    userPicture = new UserProfileCanvas();
    userPicture.setBackground(UIUtilities.BACKGROUND_COLOR);

    IconManager icons = IconManager.getInstance();
    changePhoto = new JLabel("Change Photo");
    changePhoto.setToolTipText("Upload your photo.");
    changePhoto.setForeground(UIUtilities.HYPERLINK_COLOR);
    Font font = changePhoto.getFont();
    changePhoto.setFont(font.deriveFont(font.getStyle(), font.getSize() - 2));
    changePhoto.setBackground(UIUtilities.BACKGROUND_COLOR);
    deletePhoto = new JButton(icons.getIcon(IconManager.DELETE_12));
    boolean b = canModifyPhoto();
    changePhoto.setVisible(b);
    deletePhoto.setToolTipText("Delete the photo.");
    deletePhoto.setBackground(UIUtilities.BACKGROUND_COLOR);
    UIUtilities.unifiedButtonLookAndFeel(deletePhoto);
    deletePhoto.setVisible(false);
    loginArea = new JTextField();
    boolean a = MetadataViewerAgent.isAdministrator();
    loginArea.setEnabled(a);
    loginArea.setEditable(a);
    adminBox = new JCheckBox();
    adminBox.setVisible(false);
    adminBox.setBackground(UIUtilities.BACKGROUND_COLOR);
    ownerBox = new JCheckBox();
    ownerBox.setBackground(UIUtilities.BACKGROUND_COLOR);
    activeBox = new JCheckBox();
    activeBox.setBackground(UIUtilities.BACKGROUND_COLOR);
    activeBox.setVisible(false);
    passwordButton = new JButton("Change password");
    passwordButton.setEnabled(false);
    passwordButton.setBackground(UIUtilities.BACKGROUND_COLOR);
    passwordButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            changePassword();
        }
    });
    saveButton = new JButton("Save");
    saveButton.setEnabled(false);
    saveButton.setBackground(UIUtilities.BACKGROUND_COLOR);
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GroupData g = getSelectedGroup();
            ExperimenterData exp = (ExperimenterData) model.getRefObject();
            if (exp.getDefaultGroup().getId() != g.getId())
                model.fireAdminSaving(g, true);
            view.saveData(true);
        }
    });
    manageButton = new JButton("Group");
    manageButton.setEnabled(false);
    manageButton.setBackground(UIUtilities.BACKGROUND_COLOR);
    manageButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            manageGroup();
        }
    });
    passwordNew = new JPasswordField();
    passwordNew.setBackground(UIUtilities.BACKGROUND_COLOR);
    passwordConfirm = new JPasswordField();
    passwordConfirm.setBackground(UIUtilities.BACKGROUND_COLOR);
    oldPassword = new JPasswordField();
    oldPassword.setBackground(UIUtilities.BACKGROUND_COLOR);
    items = new HashMap<String, JTextField>();
    ExperimenterData user = (ExperimenterData) model.getRefObject();
    Collection<GroupData> groups = user.getGroups();

    GroupData defaultGroup = user.getDefaultGroup();

    groupsBox = new JComboBox();
    SelectableComboBoxModel m = new SelectableComboBoxModel();
    Iterator<GroupData> i = groups.iterator();
    GroupData g;
    Selectable<DataNode> node, selected = null;
    while (i.hasNext()) {
        g = i.next();
        if (!model.isSystemGroup(g.getId(), GroupData.USER)) {
            node = new Selectable<DataNode>(new DataNode(g), true);
            if (g.getId() == defaultGroup.getId())
                selected = node;
            m.addElement(node);
        }
    }
    groupsBox.setModel(m);
    if (selected != null)
        groupsBox.setSelectedItem(selected);
    permissionsPane = new PermissionsPane(defaultGroup.getPermissions(), UIUtilities.BACKGROUND_COLOR);
    permissionsPane.disablePermissions();

    ExperimenterData logUser = model.getCurrentUser();
    if (MetadataViewerAgent.isAdministrator()) {
        //Check that the user is not the one currently logged.
        oldPassword.setVisible(false);
        adminBox.setVisible(true);
        activeBox.setVisible(true);
        adminBox.addChangeListener(this);
        active = user.isActive();
        activeBox.setSelected(active);
        activeBox.setEnabled(!model.isSelf() && !model.isSystemUser(user.getId()));
        activeBox.addChangeListener(this);
        //indicate if the user is an administrator
        admin = isUserAdministrator();
        adminBox.setSelected(admin);
        adminBox.setEnabled(!model.isSelf() && !model.isSystemUser(user.getId()));
        ownerBox.addChangeListener(this);
        ownerBox.setEnabled(!model.isSystemUser(user.getId()));
    } else {
        ownerBox.setEnabled(false);
        passwordConfirm.getDocument().addDocumentListener(new DocumentListener() {

            /**
             * Allows the user to interact with the password controls
             * depending on the value entered.
             * @see DocumentListener#removeUpdate(DocumentEvent)
             */
            public void removeUpdate(DocumentEvent e) {
                handlePasswordEntered();
            }

            /**
             * Allows the user to interact with the password controls
             * depending on the value entered.
             * @see DocumentListener#insertUpdate(DocumentEvent)
             */
            public void insertUpdate(DocumentEvent e) {
                handlePasswordEntered();
            }

            /**
             * Required by the {@link DocumentListener} I/F but 
             * no-operation implementation in our case.
             * @see DocumentListener#changedUpdate(DocumentEvent)
             */
            public void changedUpdate(DocumentEvent e) {
            }
        });
    }
    passwordNew.getDocument().addDocumentListener(new DocumentListener() {

        /**
         * Allows the user to interact with the password controls
         * depending on the value entered.
         * @see DocumentListener#removeUpdate(DocumentEvent)
         */
        public void removeUpdate(DocumentEvent e) {
            handlePasswordEntered();
        }

        /**
         * Allows the user to interact with the password controls
         * depending on the value entered.
         * @see DocumentListener#insertUpdate(DocumentEvent)
         */
        public void insertUpdate(DocumentEvent e) {
            handlePasswordEntered();
        }

        /**
         * Required by the {@link DocumentListener} I/F but
         * no-operation implementation in our case.
         * @see DocumentListener#changedUpdate(DocumentEvent)
         */
        public void changedUpdate(DocumentEvent e) {
        }
    });
    if (user.getId() == logUser.getId()) {
        MouseAdapter adapter = new MouseAdapter() {

            /** Brings up a chooser to load the user image. */
            public void mouseReleased(MouseEvent e) {
                uploadPicture();
            }

        };
        changePhoto.addMouseListener(adapter);
        deletePhoto.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                model.deletePicture();
                setUserPhoto(null);
            }
        });
        if (groups.size() > 1) {
            groupsBox.addActionListener(new ActionListener() {

                /**
                 * Listens to the change of default group.
                 */
                public void actionPerformed(ActionEvent evt) {
                    GroupData g = getSelectedGroup();
                    //update the default group
                    permissionsPane.resetPermissions(g.getPermissions());
                    permissionsPane.disablePermissions();
                    setGroupOwner(g);
                    ExperimenterData exp = (ExperimenterData) model.getRefObject();
                    saveButton.setEnabled(exp.getDefaultGroup().getId() != g.getId());
                }
            });
        }
    }
}