Example usage for java.beans PropertyChangeListener PropertyChangeListener

List of usage examples for java.beans PropertyChangeListener PropertyChangeListener

Introduction

In this page you can find the example usage for java.beans PropertyChangeListener PropertyChangeListener.

Prototype

PropertyChangeListener

Source Link

Usage

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * //from w ww.  j a  va  2s.  c om
 */
public void checkForBadAttachments() {
    int count = getNumberofBadAttachments();
    if (count == 0) {
        AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false);
        return;
    }

    URL url = null;
    JEditorPane htmlPane;
    try {
        url = new URL("http://files.specifysoftware.org/attachment_recovery.html");
        htmlPane = new JEditorPane(url);
    } catch (Exception e) {
        e.printStackTrace();
        htmlPane = new JEditorPane("text/html", //$NON-NLS-1$
                "<html><body><h1>Network Error - You must have a network conneciton to get the instructions.</H1></body>");
    }
    JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane);
    htmlPane.setEditable(false);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
    CustomDialog infoDlg = new CustomDialog((Dialog) null, "Recovery Information", true, CustomDialog.OKCANCEL,
            panel);

    infoDlg.setCancelLabel("Close");
    infoDlg.setOkLabel("Print in Browser");
    infoDlg.createUI();
    infoDlg.setSize(1024, 600);
    try {
        hookupAction(infoDlg.getOkBtn(), url != null ? url.toURI() : null);
        infoDlg.setVisible(true);

    } catch (Exception ex) {

    }

    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int totalFiles = 0;

        HashMap<Integer, Vector<Object[]>> resultsHashMap = new HashMap<Integer, Vector<Object[]>>();
        HashMap<Integer, String> tblTypeHash = new HashMap<Integer, String>();
        HashMap<Integer, String> agentHash = new HashMap<Integer, String>();
        HashMap<Integer, AttchTableModel> tableHash = new HashMap<Integer, AttchTableModel>();
        ArrayList<JTable> tableList = new ArrayList<JTable>();
        ArrayList<Integer> tableIdList = new ArrayList<Integer>();

        @Override
        protected Integer doInBackground() throws Exception {
            DataProviderSessionIFace session = null;

            try {
                // This doesn't need to include the new attachments
                int[] tableIds = { AccessionAttachment.getClassTableId(), AgentAttachment.getClassTableId(),
                        CollectingEventAttachment.getClassTableId(),
                        CollectionObjectAttachment.getClassTableId(),
                        ConservDescriptionAttachment.getClassTableId(),
                        ConservEventAttachment.getClassTableId(), DNASequencingRunAttachment.getClassTableId(),
                        FieldNotebookAttachment.getClassTableId(),
                        FieldNotebookPageAttachment.getClassTableId(),
                        FieldNotebookPageSetAttachment.getClassTableId(), LoanAttachment.getClassTableId(),
                        LocalityAttachment.getClassTableId(), PermitAttachment.getClassTableId(),
                        PreparationAttachment.getClassTableId(),
                        RepositoryAgreementAttachment.getClassTableId(), TaxonAttachment.getClassTableId() };

                Agent userAgent = AppContextMgr.getInstance().getClassObject(Agent.class);

                int totFiles = 0;
                firePropertyChange(CNT, 0, 0);
                int cnt = 0;
                for (int tableId : tableIds) {
                    Vector<Object[]> results = getImageData(userAgent.getId(), tableId, tblTypeHash);
                    if (results != null && results.size() > 0) {
                        resultsHashMap.put(tableId, results);
                        totFiles += results.size();
                        //System.out.println(tableId+"  ->  "+results.size());
                    }
                    firePropertyChange(CNT, 0, (int) ((double) cnt / (double) tableIds.length * 100.0));
                    cnt++;
                }

                if (resultsHashMap.size() == 0) // Shouldn't happen
                {
                    return null;
                }

                session = DataProviderFactory.getInstance().createSession();

                firePropertyChange(CNT, 0, 0);
                int i = 1;
                for (int tblId : resultsHashMap.keySet()) {
                    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId);

                    Vector<Object[]> dataRows = new Vector<Object[]>();
                    Vector<Object[]> results = resultsHashMap.get(tblId);
                    for (Object[] row : results) {
                        Integer agentId = (Integer) row[3];
                        String userName = agentHash.get(agentId);
                        if (userName == null) {
                            userName = BasicSQLUtils.querySingleObj(
                                    "SELECT su.Name FROM agent a INNER JOIN specifyuser su ON a.SpecifyUserID = su.SpecifyUserID WHERE a.AgentID = "
                                            + row[3]);
                            agentHash.put(agentId, userName);
                        }
                        //userName = i == 1 ? "bill.johnson" : "joe.smith";

                        int attachJoinID = (Integer) row[4];
                        String identTitle = getIdentityTitle(session, ti, attachJoinID);

                        String fullPath = (String) row[2];
                        //fullPath = StringUtils.replace(fullPath, "darwin\\", "darwin2\\");

                        //boolean doesExist = (new File(fullPath)).exists() && i != 1;
                        boolean doesExist = (new File(fullPath)).exists();
                        //String str        = i != 1 ? "/Users/joe/Desktop/xxx.png" : "/Users/bill/Desktop/xxx.png";
                        //String fullPath   = FilenameUtils.getFullPath(str) + String.format("DSC_%05d.png", i);

                        Object[] rowObjs = new Object[8];
                        rowObjs[0] = StringUtils.isEmpty(identTitle) ? ""
                                : (identTitle.length() > 30 ? identTitle.substring(0, 30) + "..." : identTitle);
                        rowObjs[1] = FilenameUtils.getName(fullPath);
                        rowObjs[2] = fullPath;
                        rowObjs[3] = userName;
                        rowObjs[4] = doesExist;
                        rowObjs[5] = Boolean.FALSE;
                        rowObjs[6] = row[0];
                        rowObjs[7] = attachJoinID;

                        dataRows.add(rowObjs);

                        if (doesExist) {
                            totalFiles++;
                        }
                        firePropertyChange(CNT, 0, (int) ((double) i / (double) totFiles * 100.0));
                        i++;
                    }
                    AttchTableModel model = new AttchTableModel(dataRows);
                    JTable table = new JTable(model);
                    tableHash.put(tblId, model);
                    tableList.add(table);
                    tableIdList.add(tblId);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                session.close();
            }

            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();

            if (tableList.size() > 0) {
                displayBadAttachments(tableList, tableIdList, resultsHashMap, tblTypeHash, tableHash,
                        totalFiles);
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg("Verifying attachments in the repository...", 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

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 w w w . ja v  a  2  s  . com*/
    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.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void openReportEditor(final String name) throws IOException {
    String formatStr = (String) JOptionPane.showInputDialog(null, "Select File Format", "File format",
            JOptionPane.QUESTION_MESSAGE, null, PluginConstants.REPORT_TEMPLATE_FORMATS,
            ReportTemplateFormat.FO.name());
    if (StringUtils.isNotBlank(formatStr)) {
        ReportTemplateFormat format = ReportTemplateFormat.valueOf(formatStr);

        InputStream is = null;//from w  w w  .j  ava 2  s .  com
        try {
            switch (format) {
            case HTML:
                is = (InputStream) reportTemplateManagerService.getFormat(name, ReportTemplateFormat.HTML);
                break;
            case CSV:
                is = (InputStream) reportTemplateManagerService.getFormat(name, ReportTemplateFormat.CSV);
                break;
            case FO:
                is = (InputStream) reportTemplateManagerService.getFormat(name, ReportTemplateFormat.FO);
                break;
            default:
                LOG.log(Level.SEVERE, String.format("Format [%s] not supported", format));
                break;
            }
        } catch (SyncopeClientException e) {
            LOG.log(Level.SEVERE,
                    String.format("Unable to get [%s] report template in [%s] format", name, format), e);
            if (ClientExceptionType.NotFound.equals(e.getType())) {
                LOG.log(Level.SEVERE,
                        String.format("Report template [%s] not found, create an empty one", name));
            } else {
                JOptionPane.showMessageDialog(null,
                        String.format("Unable to get [%s] report template in [%s] format", name, format),
                        "Connection Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            LOG.log(Level.SEVERE,
                    String.format("Unable to get [%s] report template in [%s] format", name, format), e);
            JOptionPane.showMessageDialog(null,
                    String.format("Unable to get [%s] report template in [%s] format", name, format),
                    "Generic Error", JOptionPane.ERROR_MESSAGE);
        }
        String content = is == null ? StringUtils.EMPTY : IOUtils.toString(is, encodingPattern);

        String reportTemplatesDirName = System.getProperty("java.io.tmpdir") + "/Templates/Report/";
        File reportTemplatesDir = new File(reportTemplatesDirName);
        if (!reportTemplatesDir.exists()) {
            reportTemplatesDir.mkdirs();
        }
        File file = new File(reportTemplatesDirName + name + "." + format.name().toLowerCase());
        FileWriter fw = new FileWriter(file);
        fw.write(content);
        fw.flush();
        FileObject fob = FileUtil.toFileObject(file.getAbsoluteFile());
        DataObject data = DataObject.find(fob);
        data.getLookup().lookup(OpenCookie.class).open();
        data.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(final PropertyChangeEvent evt) {
                if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) {
                    //save item remotely
                    LOG.info(String.format("Saving Report template [%s]", name));
                    saveContent();
                }
            }
        });
    }
}

From source file:at.becast.youploader.gui.FrmMain.java

public void initQueuetab() {
    JScrollPane TabQueues = new JScrollPane();
    QueuePanel = new JPanel();
    TabQueues.setViewportView(QueuePanel);

    QueuePanel.setLayout(new MigLayout("", "[875px,grow,fill]", "[][][][]"));
    JPanel buttonPanel = new JPanel();
    GridBagConstraints gbc_panel_2 = new GridBagConstraints();
    gbc_panel_2.fill = GridBagConstraints.BOTH;
    gbc_panel_2.gridx = 0;/*from w  w  w .  jav  a 2 s .c  o  m*/
    gbc_panel_2.gridy = 1;
    buttonPanel.setLayout(new FormLayout(new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC,
            FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
            FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
            FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),
            FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
            FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),
            FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;default)"),
            FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
            FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(92dlu;default)"),
            FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(46dlu;min)"), FormSpecs.RELATED_GAP_COLSPEC,
            ColumnSpec.decode("left:max(22dlu;default)"), FormSpecs.RELATED_GAP_COLSPEC,
            FormSpecs.DEFAULT_COLSPEC, },
            new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                    RowSpec.decode("max(0dlu;default)"), }));

    JButton btnStart = new JButton(LANG.getString("frmMain.start"));
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            startUploads();
        }
    });

    JLabel lblAfterUploadsFinish = new JLabel(LANG.getString("frmMain.afterfinish"));
    buttonPanel.add(lblAfterUploadsFinish, "10, 2, 7, 1");
    buttonPanel.add(btnStart, "2, 4");

    JButton btnStop = new JButton(LANG.getString("frmMain.stop"));
    btnStop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UploadMgr.stop();
        }
    });
    buttonPanel.add(btnStop, "6, 4");

    cmbAfterFinish = new JComboBox<Object>();
    cmbAfterFinish.setModel(new DefaultComboBoxModel<Object>(new String[] {
            LANG.getString("frmMain.afterfinish.donothing"), LANG.getString("frmMain.afterfinish.suspend"),
            LANG.getString("frmMain.afterfinish.shutdown") }));
    buttonPanel.add(cmbAfterFinish, "10, 4, 7, 1, fill, default");

    JLabel lblUploads = new JLabel(LANG.getString("frmMain.uploads") + ":");
    buttonPanel.add(lblUploads, "18, 4, right, fill");

    JSlider slider = new JSlider();
    slider.setPaintTicks(true);
    slider.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            JSlider s = (JSlider) evt.getSource();
            UploadMgr.setUploadlimit(s.getValue());
        }
    });
    slider.setMajorTickSpacing(1);
    slider.setMinorTickSpacing(1);

    slider.setMinimum(1);
    slider.setMaximum(5);
    slider.setValue(1);
    slider.setSnapToTicks(true);
    slider.setPaintLabels(true);
    buttonPanel.add(slider, "20, 4, fill, fill");

    JLabel lblUploadSpeed = new JLabel(LANG.getString("frmMain.uploadspeed") + ":");
    lblUploadSpeed.setHorizontalAlignment(SwingConstants.TRAILING);
    buttonPanel.add(lblUploadSpeed, "24, 4");

    spinner = new JSpinner();
    spinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(10)));
    spinner.setEditor(new SpeedValuesSpinnerEditor(spinner));
    spinner.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            JSpinner s = (JSpinner) e.getSource();
            speed = Integer.parseInt(s.getValue().toString());
            Main.s.put("speed", String.valueOf(speed));
            UploadMgr.setLimit(speed);
        }
    });
    spinner.setValue(speed);
    buttonPanel.add(spinner, "26, 4");

    JLabel lblKbps = new JLabel("kbps");
    buttonPanel.add(lblKbps, "28, 4");

    JPanel TabQueue = new JPanel();
    TabbedPane.addTab(LANG.getString("frmMain.Tabs.Queue"), null, TabQueue, null);
    TabQueue.setLayout(new BorderLayout(0, 0));

    TabQueue.add(buttonPanel, BorderLayout.SOUTH);

    TabQueue.add(TabQueues, BorderLayout.CENTER);
}

From source file:org.isatools.isacreator.gui.formelements.SubForm.java

private void removalConfirmation(final FieldTypes whatIsBeingRemoved) {
    // delete reference to protocol in subform

    // add one to take into account the model and the initial column which contains fields names.
    final int selectedItem = scrollTable.getSelectedColumn() + 1;

    // check to ensure the value isn't 0, if it is, nothing is selected in the table since -1 (value returned by model if
    // no column is selected + 1 = 0!)
    if ((selectedItem != 0) && (dataEntryForm != null)) {
        String displayText;// ww w . ja v  a2  s  . c o  m
        if ((whatIsBeingRemoved == FieldTypes.FACTOR) || (whatIsBeingRemoved == FieldTypes.PROTOCOL)) {
            displayText = "<html>" + "<b>Confirm deletion of " + fieldType + "</b>" + "<p>Deleting this "
                    + fieldType + " will result in all " + fieldType + "s of this type in subsequent assays</p>"
                    + "<p>being deleted too! Do you wish to continue?</p>" + "</html>";
        } else {
            displayText = "<html>" + "<b>Confirm deletion of " + fieldType + "</b>" + "<p>Deleting this "
                    + fieldType + " will result in its complete removal from this experiment annotation!</p>"
                    + "<p>Do you wish to continue?</p>" + "</html>";
        }

        JOptionPane optionPane = new JOptionPane(displayText, JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.YES_NO_OPTION);
        optionPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if (event.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)) {
                    int lastOptionAnswer = Integer.valueOf(event.getNewValue().toString());

                    if (lastOptionAnswer == JOptionPane.YES_OPTION) {
                        removeItem(selectedItem);
                        ApplicationManager.getCurrentApplicationInstance().hideSheet();
                    } else {
                        // just hide the sheet and cancel further actions!
                        ApplicationManager.getCurrentApplicationInstance().hideSheet();
                    }
                }
            }
        });
        optionPane.setIcon(confirmRemoveColumn);
        UIHelper.applyOptionPaneBackground(optionPane, UIHelper.BG_COLOR);
        ApplicationManager.getCurrentApplicationInstance()
                .showJDialogAsSheet(optionPane.createDialog(this, "Confirm Delete"));
    } else {
        removeColumn(selectedItem);
    }
}

From source file:edu.ku.brc.specify.config.init.DatabasePanel.java

/**
 * //from  w  w  w.  j a  v  a  2 s . co  m
 */
public void createDB() {
    getValues(properties);

    final String databaseName = dbNameTxt.getText();
    final String dbUserName = usernameTxt.getText();
    final String dbPwd = passwordTxt.getText();
    final String hostName = hostNameTxt.getText();

    if (UIRegistry.isMobile()) {
        DBConnection.clearMobileMachineDir();
        File tmpDir = DBConnection.getMobileMachineDir(databaseName);
        UIRegistry.setEmbeddedDBPath(tmpDir.getAbsolutePath());
    }

    final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem();
    String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            databaseName, dbUserName, dbPwd, driverInfo.getName());
    //System.err.println(connStrInitial);

    DBConnection.checkForEmbeddedDir(connStrInitial);

    DBConnection.getInstance().setDriverName(driverInfo.getName());
    DBConnection.getInstance().setServerName(hostName);

    VerifyStatus status = verifyDatabase(properties);
    if ((isOK == null || !isOK) && status == VerifyStatus.OK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        label.setText(getResourceString("CONN_DB"));
        createDBBtn.setVisible(false);

        setUIEnabled(false);

        DatabasePanel.this.label.setForeground(Color.BLACK);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;

                DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                List<PermissionInfo> perms = null;

                boolean dbmsOK = false;
                if (driverInfo.isEmbedded()) {
                    if (checkForProcesses) {
                        ProcessListUtil.checkForMySQLProcesses(null);
                        checkForProcesses = false;
                    }

                    if (UIRegistry.isMobile()) {
                        File mobileTmpDir = DBConnection.getMobileMachineDir();
                        if (!mobileTmpDir.exists()) {
                            if (!mobileTmpDir.mkdirs()) {
                                System.err.println(
                                        "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!");
                                // throw exception
                            }
                            DBConnection.setCopiedToMachineDisk(true);
                        }
                    }

                    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                            hostName, databaseName, dbUserName, dbPwd, driverInfo.getName());
                    if (driverInfo.isEmbedded()) {
                        //System.err.println(newConnStr);
                        try {
                            Class.forName(driverInfo.getDriverClassName());

                            // This call will create the database if it doesn't exist
                            DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                    driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName,
                                    dbPwd);
                            testDB.getConnection(); // Opens the connection

                            if (testDB != null) {
                                testDB.close();
                            }
                            dbmsOK = true;

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        DBConnection.getInstance().setDatabaseName(null);
                    }
                } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) {
                    perms = mgr.getPermissionsForCurrentUser();
                    Pair<List<PermissionInfo>, List<PermissionInfo>> missingPerms = PermissionInfo
                            .getMissingPerms(perms, createDBPerms, databaseName);
                    if (missingPerms.getFirst().size() > 0) {
                        final String missingPermStr = PermissionInfo.getMissingPermissionString(mgr,
                                missingPerms.getFirst(), databaseName);
                        SwingUtilities.invokeLater(new Runnable() {

                            /* (non-Javadoc)
                             * @see java.lang.Runnable#run()
                             */
                            @Override
                            public void run() {
                                UIRegistry.showLocalizedError("SEC_MISSING_PERMS", dbUserName, missingPermStr);
                            }

                        });
                        dbmsOK = false;
                    } else {
                        dbmsOK = true;
                    }
                    mgr.close();
                }

                if (dbmsOK) {
                    properties.put(DB_SKIP_CREATE, false);
                    if (perms != null) {
                        properties.put(DBUSERPERMS, perms);
                    }

                    firePropertyChange(PROPNAME, 0, 1);

                    try {
                        SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName,
                                dbPwd); // false means create new database, true means update

                        String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create,
                                hostName, databaseName);
                        if (connStr == null) {
                            connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                                    hostName, databaseName);
                        }

                        firePropertyChange(PROPNAME, 0, 2);

                        // tryLogin sets up DBConnection
                        if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                                dbNameTxt.getText(), connStr, dbUserName, dbPwd)) {

                            if (!checkEngineCharSet(properties)) {
                                return false;
                            }
                            isOK = true;

                            firePropertyChange(PROPNAME, 0, 3);

                            Thumbnailer thumb = Thumbnailer.getInstance();
                            File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml");
                            thumb.registerThumbnailers(thumbFile);
                            thumb.setQuality(0.5f);
                            thumb.setMaxSize(128, 128);

                            File attLoc = UIRegistry.getAppDataSubDir("AttachmentStorage", true);
                            AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc);
                            AttachmentUtils.setAttachmentManager(attachMgr);
                            AttachmentUtils.setThumbnailer(thumb);

                        } else {
                            errorKey = "NO_LOGIN_ROOT";
                        }
                    } catch (Exception ex) {
                        errorKey = "DB_UNRECOVERABLE";
                    }
                } else {
                    errorKey = "NO_CONN_ROOT";
                    mgr.close();
                }
                return null;
            }

            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#done()
             */
            @Override
            protected void done() {
                super.done();

                setUIEnabled(true);

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                updateBtnUI();
                createDBBtn.setVisible(!isOK);

                if (isOK) {
                    label.setText(UIRegistry.getResourceString("DB_CREATED"));
                    setUIEnabled(false);

                } else {
                    label.setText(UIRegistry.getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB"));
                    UIRegistry.showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB");
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (PROPNAME.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "BLD_SCHEMA";
                        break;
                    case 2:
                        key = "DB_FRST_LOGIN";
                        break;
                    case 3:
                        key = "BLD_CACHE";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        DatabasePanel.this.label.setText(UIRegistry.getResourceString(key));
                    }
                }
            }
        });
        worker.execute();

    } else if (status == VerifyStatus.ERROR) {
        errorKey = "NO_LOGIN_ROOT";
        DatabasePanel.this.label.setText(UIRegistry.getResourceString(errorKey));
        DatabasePanel.this.label.setForeground(Color.RED);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                UIRegistry.getTopWindow().pack();
            }
        });
    }
}

From source file:ca.uhn.hl7v2.testpanel.ui.editor.Hl7V2MessageEditorPanel.java

private void initLocal() {

    myDocumentListener = new DocumentListener() {

        public void changedUpdate(DocumentEvent theE) {
            ourLog.info("Document change: " + theE);
            handleChange(theE);/*ww w.j a  va2  s.co  m*/
        }

        private void handleChange(DocumentEvent theE) {
            myDontRespondToSourceMessageChanges = true;
            try {
                long start = System.currentTimeMillis();

                String newSource = myMessageEditor.getText();
                int changeStart = theE.getOffset();
                int changeEnd = changeStart + theE.getLength();
                myMessage.updateSourceMessage(newSource, changeStart, changeEnd);

                ourLog.info("Handled document update in {} ms", System.currentTimeMillis() - start);
            } finally {
                myDontRespondToSourceMessageChanges = false;
            }
        }

        public void insertUpdate(DocumentEvent theE) {
            ourLog.info("Document insert: " + theE);
            handleChange(theE);
        }

        public void removeUpdate(DocumentEvent theE) {
            ourLog.info("Document removed: " + theE);
            handleChange(theE);
        }
    };
    myMessageEditor.getDocument().addDocumentListener(myDocumentListener);

    myMessageEditor.addCaretListener(new CaretListener() {

        public void caretUpdate(final CaretEvent theE) {
            removeMostHighlights();
            if (!myDisableCaretUpdateHandling) {
                myController.invokeInBackground(new Runnable() {
                    @Override
                    public void run() {
                        myMessage.setHighlitedPathBasedOnRange(new Range(theE.getDot(), theE.getMark()));
                        myTreePanel.repaint();
                    }
                });
            }
        }
    });

    updateOutboundConnectionsBox();
    myOutboundConnectionsListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            updateOutboundConnectionsBox();
        }
    };
    myController.getOutboundConnectionList().addPropertyChangeListener(OutboundConnectionList.PROP_LIST,
            myOutboundConnectionsListener);

    myOutboundInterfaceCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent theE) {
            if (!myOutboundInterfaceComboModelIsUpdating) {
                updateSendButton();
            }
        }

    });

    JMenuItem copyMenuItem = new JMenuItem("Copy to Clipboard");
    copyMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent theE) {
            String selection = myTerserPathTextField.getText();
            StringSelection data = new StringSelection(selection);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(data, data);
        }
    });
    myTerserPathPopupMenu.add(copyMenuItem);

    myProfilesListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent theEvt) {
            myProfileComboboxModel.update();
            registerProfileNamesListeners();
        }
    };
    myController.getProfileFileList().addPropertyChangeListener(ProfileFileList.PROP_FILES, myProfilesListener);
    registerProfileNamesListeners();

    myProfilesNamesListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent theEvt) {
            myProfileComboboxModel.update();
        }
    };

}

From source file:edu.ku.brc.af.ui.forms.ResultSetController.java

/**
 * //  www.  ja v  a 2  s . c om
 */
private static void registerFocusListener() {
    final KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    focusManager.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            Component permanentFocusOwner = null;
            String propName = e.getPropertyName();
            if (propName.equals("permanentFocusOwner")) {
                permanentFocusOwner = focusManager.getFocusOwner();
            }
            Component comp = permanentFocusOwner;
            while (comp != null && !(comp instanceof MultiView)) {
                comp = comp.getParent();
            }

            ResultSetController rsc = null;
            boolean fnd = false;
            if (comp instanceof MultiView) {
                FormViewObj fvo = ((MultiView) comp).getCurrentViewAsFormViewObj();
                if (fvo != null && fvo.getRsController() != null) {
                    rsc = fvo.getRsController();
                    if (currentFocusedRS == null || currentFocusedRS != rsc) {
                        currentFocusedRS = rsc;
                        fnd = true;
                    }
                }
            }

            if (!fnd) {
                currentFocusedRS = backStopRS;
            }

            installRS(currentFocusedRS);

        }
    });
}

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

/**
 * Returns the collection of attachments.
 * /*from  ww w . jav  a  2s  .  co  m*/
 * @param src The source of the mouse pressed.
 * @param location The location of the mouse pressed.
 */
void removeAttachedFiles(Component src, Point location) {
    if (!generalPane.hasAttachmentsToUnlink())
        return;
    if (model.isAdministrator() || model.isGroupLeader()) {
        if (docMenu == null) {
            docMenu = new PermissionMenu(PermissionMenu.REMOVE, "Attachments");
            docMenu.addPropertyChangeListener(new PropertyChangeListener() {

                public void propertyChange(PropertyChangeEvent evt) {
                    String n = evt.getPropertyName();
                    if (PermissionMenu.SELECTED_LEVEL_PROPERTY.equals(n)) {
                        List<FileAnnotationData> toRemove = model
                                .getFileAnnotatationsByLevel((Integer) evt.getNewValue());
                        model.fireFileAnnotationRemoveCheck(toRemove);
                    }
                }
            });
        }
        docMenu.show(src, location.x, location.y);
        return;
    }
    SwingUtilities.convertPointToScreen(location, src);
    MessageBox box = new MessageBox(model.getRefFrame(), "Remove All Attachments",
            "Are you sure you want to remove all Attachments?");
    Dimension d = box.getPreferredSize();
    Point p = new Point(location.x - d.width / 2, location.y);
    if (box.showMsgBox(p) == MessageBox.YES_OPTION) {
        List<FileAnnotationData> list = generalPane.removeAttachedFiles();
        if (list.size() > 0)
            model.fireFileAnnotationRemoveCheck(list);
    }
}

From source file:op.care.med.inventory.DlgNewStocks.java

private void btnMedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMedActionPerformed

    //        String pzn = MedPackageTools.parsePZN(txtMedSuche.getText());
    final JidePopup popup = new JidePopup();

    WizardDialog wizard = new MedProductWizard(new Closure() {
        @Override/*from   w  w  w.  j av a 2s.com*/
        public void execute(Object o) {
            if (o != null) {
                MedPackage aPackage = (MedPackage) o;
                txtMedSuche.setText(aPackage.getPzn());
            }
            popup.hidePopup();

        }
    }).getWizard();

    popup.setMovable(false);
    popup.setPreferredSize((new Dimension(800, 450)));
    popup.setResizable(false);
    popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
    popup.getContentPane().add(wizard.getContentPane());
    popup.setOwner(btnMed);
    popup.removeExcludedComponent(btnMed);
    popup.setTransient(true);
    popup.setDefaultFocusComponent(wizard.getContentPane());
    popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            OPDE.debug("popup property: " + propertyChangeEvent.getPropertyName() + " value: "
                    + propertyChangeEvent.getNewValue() + " compCount: "
                    + popup.getContentPane().getComponentCount());
            popup.getContentPane().getComponentCount();
        }
    });

    GUITools.showPopup(popup, SwingConstants.WEST);

    //        popup.showPopup(new Insets(-5, wizard.getPreferredSize().width * -1 - 200, -5, -100), btnMed);

}