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:visolate.Visolate.java

private JPanel getInitialXPanel() {
    if (myInitialXPanel == null) {
        myInitialXPanel = new JPanel();
        myInitialXPanel.setLayout(new BorderLayout());
        myInitialXPanel.add(new JLabel("X"), BorderLayout.WEST);
        myInitialXPanel.setToolTipText("Left side is at this coordinate (mm or inch)");
        myInitialXPanel.setEnabled(gCodeWriter.getIsAbsolute());
        final JTextField field = new JTextField(NumberFormat.getInstance().format(gCodeWriter.getXOffset()));
        myInitialXPanel.add(field, BorderLayout.CENTER);
        myInitialXPanel.addPropertyChangeListener("enabled", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                field.setEnabled(myInitialXPanel.isEnabled());
            }//  ww w .j  a v  a  2s . c om
        });
        field.setEnabled(myInitialXPanel.isEnabled());
        field.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent evt) {
                try {
                    gCodeWriter.setXOffset(NumberFormat.getInstance().parse(field.getText()).doubleValue());
                } catch (ParseException e) {
                }
                field.setText(NumberFormat.getInstance().format(gCodeWriter.getXOffset()));
            }
        });
    }
    return myInitialXPanel;
}

From source file:VASSAL.launch.ModuleManagerWindow.java

public ModuleManagerWindow() {
    setTitle("VASSAL");
    setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

    ApplicationIcons.setFor(this);

    final AbstractAction shutDownAction = new AbstractAction() {
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            if (!AbstractLaunchAction.shutDown())
                return;

            final Prefs gl = Prefs.getGlobalPrefs();
            try {
                gl.write();/*from www  .ja  v  a2 s  .  c  o  m*/
                gl.close();
            } catch (IOException ex) {
                WriteErrorDialog.error(ex, gl.getFile());
            } finally {
                IOUtils.closeQuietly(gl);
            }

            logger.info("Exiting");
            System.exit(0);
        }
    };
    shutDownAction.putValue(Action.NAME, Resources.getString(Resources.QUIT));

    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            shutDownAction.actionPerformed(null);
        }
    });

    // setup menubar and actions
    final MenuManager mm = MenuManager.getInstance();
    final MenuBarProxy mb = mm.getMenuBarProxyFor(this);

    // file menu
    final MenuProxy fileMenu = new MenuProxy(Resources.getString("General.file"));
    fileMenu.setMnemonic(Resources.getString("General.file.shortcut").charAt(0));

    fileMenu.add(mm.addKey("Main.play_module"));
    fileMenu.add(mm.addKey("Main.edit_module"));
    fileMenu.add(mm.addKey("Main.new_module"));
    fileMenu.add(mm.addKey("Main.import_module"));
    fileMenu.addSeparator();

    if (!SystemUtils.IS_OS_MAC_OSX) {
        fileMenu.add(mm.addKey("Prefs.edit_preferences"));
        fileMenu.addSeparator();
        fileMenu.add(mm.addKey("General.quit"));
    }

    // tools menu
    final MenuProxy toolsMenu = new MenuProxy(Resources.getString("General.tools"));

    // Initialize Global Preferences
    Prefs.getGlobalPrefs().getEditor().initDialog(this);
    Prefs.initSharedGlobalPrefs();

    final BooleanConfigurer serverStatusConfig = new BooleanConfigurer(SHOW_STATUS_KEY, null, Boolean.FALSE);
    Prefs.getGlobalPrefs().addOption(null, serverStatusConfig);

    dividerLocationConfig = new IntConfigurer(DIVIDER_LOCATION_KEY, null, -10);
    Prefs.getGlobalPrefs().addOption(null, dividerLocationConfig);

    toolsMenu.add(new CheckBoxMenuItemProxy(new AbstractAction(Resources.getString("Chat.server_status")) {
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            serverStatusView.toggleVisibility();
            serverStatusConfig.setValue(serverStatusConfig.booleanValue() ? Boolean.FALSE : Boolean.TRUE);
            if (serverStatusView.isVisible()) {
                setDividerLocation(getPreferredDividerLocation());
            }
        }
    }, serverStatusConfig.booleanValue()));

    // help menu
    final MenuProxy helpMenu = new MenuProxy(Resources.getString("General.help"));
    helpMenu.setMnemonic(Resources.getString("General.help.shortcut").charAt(0));

    helpMenu.add(mm.addKey("General.help"));
    helpMenu.add(mm.addKey("Main.tour"));
    helpMenu.addSeparator();
    helpMenu.add(mm.addKey("UpdateCheckAction.update_check"));
    helpMenu.add(mm.addKey("Help.error_log"));

    if (!SystemUtils.IS_OS_MAC_OSX) {
        helpMenu.addSeparator();
        helpMenu.add(mm.addKey("AboutScreen.about_vassal"));
    }

    mb.add(fileMenu);
    mb.add(toolsMenu);
    mb.add(helpMenu);

    // add actions
    mm.addAction("Main.play_module", new Player.PromptLaunchAction(this));
    mm.addAction("Main.edit_module", new Editor.PromptLaunchAction(this));
    mm.addAction("Main.new_module", new Editor.NewModuleLaunchAction(this));
    mm.addAction("Main.import_module", new Editor.PromptImportLaunchAction(this));
    mm.addAction("Prefs.edit_preferences", Prefs.getGlobalPrefs().getEditor().getEditAction());
    mm.addAction("General.quit", shutDownAction);

    URL url = null;
    try {
        url = new File(Documentation.getDocumentationBaseDir(), "README.html").toURI().toURL();
    } catch (MalformedURLException e) {
        ErrorDialog.bug(e);
    }
    mm.addAction("General.help", new ShowHelpAction(url, null));

    mm.addAction("Main.tour", new LaunchTourAction(this));
    mm.addAction("AboutScreen.about_vassal", new AboutVASSALAction(this));
    mm.addAction("UpdateCheckAction.update_check", new UpdateCheckAction(this));
    mm.addAction("Help.error_log", new ShowErrorLogAction(this));

    setJMenuBar(mm.getMenuBarFor(this));

    // Load Icons
    moduleIcon = new ImageIcon(getClass().getResource("/images/mm-module.png"));
    activeExtensionIcon = new ImageIcon(getClass().getResource("/images/mm-extension-active.png"));
    inactiveExtensionIcon = new ImageIcon(getClass().getResource("/images/mm-extension-inactive.png"));
    openGameFolderIcon = new ImageIcon(getClass().getResource("/images/mm-gamefolder-open.png"));
    closedGameFolderIcon = new ImageIcon(getClass().getResource("/images/mm-gamefolder-closed.png"));
    fileIcon = new ImageIcon(getClass().getResource("/images/mm-file.png"));

    // build module controls
    final JPanel moduleControls = new JPanel(new BorderLayout());
    modulePanelLayout = new CardLayout();
    moduleView = new JPanel(modulePanelLayout);
    buildTree();
    final JScrollPane scroll = new JScrollPane(tree);
    moduleView.add(scroll, "modules");

    final JEditorPane l = new JEditorPane("text/html", Resources.getString("ModuleManager.quickstart"));
    l.setEditable(false);

    // Try to get background color and font from LookAndFeel;
    // otherwise, use dummy JLabel to get color and font.
    Color bg = UIManager.getColor("control");
    Font font = UIManager.getFont("Label.font");

    if (bg == null || font == null) {
        final JLabel dummy = new JLabel();
        if (bg == null)
            bg = dummy.getBackground();
        if (font == null)
            font = dummy.getFont();
    }

    l.setBackground(bg);
    ((HTMLEditorKit) l.getEditorKit()).getStyleSheet()
            .addRule("body { font: " + font.getFamily() + " " + font.getSize() + "pt }");

    l.addHyperlinkListener(BrowserSupport.getListener());

    // FIXME: use MigLayout for this!
    // this is necessary to get proper vertical alignment
    final JPanel p = new JPanel(new GridBagLayout());
    final GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    p.add(l, c);

    moduleView.add(p, "quickStart");
    modulePanelLayout.show(moduleView, getModuleCount() == 0 ? "quickStart" : "modules");
    moduleControls.add(moduleView, BorderLayout.CENTER);
    moduleControls.setBorder(new TitledBorder(Resources.getString("ModuleManager.recent_modules")));

    add(moduleControls);

    // build server status controls
    final ServerStatusView serverStatusControls = new ServerStatusView(new CgiServerStatus());
    serverStatusControls.setBorder(new TitledBorder(Resources.getString("Chat.server_status")));

    serverStatusView = new ComponentSplitter().splitRight(moduleControls, serverStatusControls, false);
    serverStatusView.revalidate();

    // show the server status controls according to the prefs
    if (serverStatusConfig.booleanValue()) {
        serverStatusView.showComponent();
    }

    setDividerLocation(getPreferredDividerLocation());
    serverStatusView.addPropertyChangeListener("dividerLocation", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            setPreferredDividerLocation((Integer) e.getNewValue());
        }
    });

    final Rectangle r = Info.getScreenBounds(this);
    serverStatusControls.setPreferredSize(new Dimension((int) (r.width / 3.5), 0));

    setSize(3 * r.width / 4, 3 * r.height / 4);

    // Save/load the window position and size in prefs
    final PositionOption option = new PositionOption(PositionOption.key + "ModuleManager", this);
    Prefs.getGlobalPrefs().addOption(option);
}

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

/** Brings up the folder chooser. */
private void download() {
    JFrame f = MetadataViewerAgent.getRegistry().getTaskBar().getFrame();

    List<DataObject> list = view.getSelectedObjects();
    ImageData image = view.getImage();/*from  www .j  a  v  a2 s  .c  om*/
    int type = FileChooser.SAVE;
    List<String> paths = new ArrayList<String>();
    if (list != null && list.size() > 1) {
        type = FileChooser.FOLDER_CHOOSER;
        Iterator<DataObject> i = list.iterator();
        DataObject data;
        while (i.hasNext()) {
            data = i.next();
            if (data instanceof ImageData) {
                paths.add(FilenameUtils.getName(((ImageData) data).getName()));
            }
        }
    }

    FileChooser chooser = new FileChooser(f, type, FileChooser.DOWNLOAD_TEXT, FileChooser.DOWNLOAD_DESCRIPTION,
            null, true);
    try {
        File file = UIUtilities.getDefaultFolder();
        if (file != null)
            chooser.setCurrentDirectory(file);
    } catch (Exception ex) {
    }
    if (type == FileChooser.SAVE)
        chooser.setSelectedFileFull(image.getName());

    IconManager icons = IconManager.getInstance();
    chooser.setTitleIcon(icons.getIcon(IconManager.DOWNLOAD_48));
    chooser.setApproveButtonText(FileChooser.DOWNLOAD_TEXT);
    chooser.setCheckOverride(true);
    chooser.setSelectedFiles(paths);
    chooser.addPropertyChangeListener(new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent evt) {
            String name = evt.getPropertyName();
            FileChooser src = (FileChooser) evt.getSource();
            if (FileChooser.APPROVE_SELECTION_PROPERTY.equals(name)) {
                File path = null;
                if (src.getChooserType() == FileChooser.FOLDER_CHOOSER) {
                    path = new File((String) evt.getNewValue());
                } else {
                    File[] files = (File[]) evt.getNewValue();
                    if (files == null || files.length == 0)
                        return;
                    path = files[0];
                }
                if (path == null) {
                    path = UIUtilities.getDefaultFolder();
                }
                model.download(path, src.isOverride());
            }
        }
    });
    chooser.centerDialog();
}

From source file:gda.gui.mca.McaGUI.java

private void makeTcaControlDialog() {
    if (tcaControlPanel == null) {
        tcaControlPanel = new TcaPanel();
        tcaDialog = new JDialog();
        Object[] options = { "OK" };
        Object[] array = { tcaControlPanel };

        // Create the JOptionPane.
        final JOptionPane optionPane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_OPTION,
                null, options, options[0]);
        optionPane.addPropertyChangeListener(new PropertyChangeListener() {

            @Override/*  w w w .  j  a va 2  s.co m*/
            public void propertyChange(PropertyChangeEvent e) {
                String prop = e.getPropertyName();

                if (isVisible() && (e.getSource() == optionPane) && (JOptionPane.VALUE_PROPERTY.equals(prop)
                        || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
                    Object value = optionPane.getValue();

                    if (value == JOptionPane.UNINITIALIZED_VALUE) {
                        // ignore reset
                        return;
                    }

                    // Reset the JOptionPane's value.
                    // If you don't do this, then if the user
                    // presses the same button next time, no
                    // property change event will be fired.
                    optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);

                    if ("OK".equals(value)) {

                        tcaDialog.setVisible(false);
                    }
                }

            }

        });
        tcaDialog.setContentPane(optionPane);
        tcaDialog.pack();
        tcaDialog.setTitle("TCA Controls");
        tcaDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    }

}

From source file:pipeline.GUI_utils.ListOfPointsView.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*ww w  .  j  a v a  2s  . c  o m*/
public void show() {
    if (frame != null)
        frame.toFront();
    if (table == null) {
        spreadsheetEngine = new DependencyEngine(new BasicEngineProvider());
        setupTableModel(points);
        silenceUpdates.incrementAndGet();
        table = new JXTablePerColumnFiltering(tableModel);

        table.setRolloverEnabled(true);
        // table.setDragEnabled(true);
        table.setFillsViewportHeight(false);
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.setShowGrid(true);
        table.setShowHorizontalLines(true);
        table.setColumnSelectionAllowed(true);
        table.setRowSelectionAllowed(true);
        table.setColumnControlVisible(true);
        table.setHighlighters(new Highlighter[] { HighlighterFactory.createAlternateStriping() });

        table.addPropertyChangeListener("horizontalScrollEnabled", new PropertyChangeListener() {

            JViewport viewPort, filteringViewPort, columnDescViewPort;
            int lastX;

            ChangeListener scrollListener = new ChangeListener() {

                @Override
                public void stateChanged(ChangeEvent e) {
                    if (viewPort == null || filteringViewPort == null) {
                        return;
                    }
                    Point position = viewPort.getViewPosition();
                    if (position.x == lastX) {
                        return;
                    }
                    filteringViewPort.setViewPosition(position);
                    columnDescViewPort.setViewPosition(position);
                    lastX = position.x;
                }

            };

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (viewPort != null) {
                    viewPort.removeChangeListener(scrollListener);
                }
                if (evt.getNewValue().equals(true)) {
                    viewPort = getTableViewPort(table);
                    if (viewPort == null) {
                        return;
                    }
                    table.filteringTable.setHorizontalScrollEnabled(true);
                    table.tableForColumnDescriptions.setHorizontalScrollEnabled(true);
                    table.updateFilteringTableSetup();
                    filteringViewPort = getTableViewPort(table.filteringTable);
                    columnDescViewPort = getTableViewPort(table.tableForColumnDescriptions);
                    viewPort.addChangeListener(scrollListener);
                    scrollListener.stateChanged(null);
                } else {
                    table.filteringTable.setHorizontalScrollEnabled(false);
                    table.tableForColumnDescriptions.setHorizontalScrollEnabled(false);
                }
            }
        });

        modelForColumnDescriptions = new dataModelAllEditable(1, tableModel.getColumnCount());
        Vector<String> rowVector0 = (Vector<String>) modelForColumnDescriptions.getDataVector().get(0);
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            rowVector0.setElementAt(tableModel.getColumnName(j), j);
        }

        boolean done;
        do {
            done = true;
            for (TableColumn i : table.getColumns(true)) {
                TableColumnExt iCast = (TableColumnExt) i;
                if (iCast.getTitle().equals("Class") || iCast.getTitle().equals("c")
                        || iCast.getTitle().equals("t") || iCast.getTitle().equals("clusterID")
                        || iCast.getTitle().equals("userCell 2") || iCast.getTitle().equals("userCell 3")) {
                    if (iCast.isVisible()) {
                        iCast.setVisible(false);
                        done = false;
                        break;
                    }
                }
            }
        } while (!done);

        SwingUtilities.invokeLater(modelForColumnDescriptions::fireTableDataChanged);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(2000, 2000));

        updateColumnDescriptions();
        silenceUpdates.decrementAndGet();

        setSpreadsheetColumnEditorAndRenderer();

        tableForColumnDescriptions = new JXTable(modelForColumnDescriptions);
        table.tableForColumnDescriptions = tableForColumnDescriptions;

        JScrollPane jScrollPaneForNames = new JScrollPane(tableForColumnDescriptions);
        jScrollPaneForNames.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        JButton createScatterPlotButton = new JButton("Scatter plot from selected columns");
        controlPanel.add(createScatterPlotButton);
        createScatterPlotButton.setActionCommand("Scatter plot from selected columns");
        createScatterPlotButton.addActionListener(this);

        realTimeUpdateCheckbox = new JCheckBox("Update display in real time");
        controlPanel.add(realTimeUpdateCheckbox);
        realTimeUpdateCheckbox.setActionCommand("Update display in real time");
        realTimeUpdateCheckbox.addActionListener(this);

        JButton forceUpdate = new JButton("Force display update");
        controlPanel.add(forceUpdate);
        forceUpdate.setActionCommand("Force display update");
        forceUpdate.addActionListener(this);

        JButton extendFormula = new JButton("Extend formula to column");
        controlPanel.add(extendFormula);
        extendFormula.setActionCommand("Extend formula to column");
        extendFormula.addActionListener(this);

        JButton saveFormulas = new JButton("Save user formulas...");
        saveFormulas.addActionListener(this);
        saveFormulas.setActionCommand("Save user formulas");
        controlPanel.add(saveFormulas);

        JButton reloadFormulas = new JButton("Reload user formulas...");
        reloadFormulas.addActionListener(this);
        reloadFormulas.setActionCommand("Reload user formulas");
        controlPanel.add(reloadFormulas);

        controlPanel.add(new JLabel("Color with:"));
        coloringComboBox = new JComboBox();
        controlPanel.add(coloringComboBox);
        DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) coloringComboBox.getModel();
        coloringComboBox.addActionListener(this);

        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            comboBoxModel.addElement(tableModel.getColumnName(i));
        }

        JButton saveTableToFile = new JButton("Save table to file");
        controlPanel.add(saveTableToFile);
        saveTableToFile.setActionCommand("Save table to file");
        saveTableToFile.addActionListener(this);

        /*
        final JCheckBox useCalibration = new JCheckBox("Use calibration");
        useCalibration.addActionListener(e -> {
           if (points == null)
              return;
           boolean selected = useCalibration.isSelected();
           if (selected && !(points instanceof PluginIOCalibrable)) {
              Utils.displayMessage("Type " + points.getClass().getName() + " does not have calibration", true,
             LogLevel.ERROR);
              return;
           }
           PluginIOCalibrable calibrable = (PluginIOCalibrable) points;
           if (selected && (calibrable.getCalibration() == null)) {
              Utils.displayMessage("Calibration information is not present in the segmentation; one "
             + "way of adding it is to give the source image (with calibration) as an input "
             + "to the active contour plugin", true, LogLevel.ERROR);
              return;
           }
           float xyCalibration = selected ? ((float) calibrable.getCalibration().pixelWidth) : 0;
           float zCalibration = selected ? ((float) calibrable.getCalibration().pixelDepth) : 0;
           updateCalibration(xyCalibration, zCalibration);
        });
        PluginIOCalibrable calibrable = null;
        if (points instanceof PluginIOCalibrable)
           calibrable = (PluginIOCalibrable) points;
        boolean calibrationPresent = calibrable != null && calibrable.getCalibration() != null;
        useCalibration.setSelected(calibrationPresent);
        if (calibrationPresent) {
           updateCalibration((float) calibrable.getCalibration().pixelWidth,
          (float) calibrable.getCalibration().pixelDepth);
        }
        controlPanel.add(useCalibration);
        */

        frame = new JFrame(points.getName());
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        listener = new WindowListenerWeakRef(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                close();// So all references to data are nulled, to ensure garbage collection
            }

        });
        frame.addWindowListener(listener);

        frame.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = GridBagConstraints.RELATIVE;
        c.weighty = 0.75;
        c.weightx = 1.0;
        c.gridwidth = 1;
        c.gridheight = 1;

        frame.add(scrollPane, c);

        c.weighty = 0.0;
        JScrollPane scrollPane2 = new JScrollPane(table.filteringTable);
        scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane2.setMinimumSize(new Dimension(1, 250));
        frame.add(scrollPane2, c);

        c.weighty = 0.0;
        jScrollPaneForNames.setMinimumSize(new Dimension(1, 40));
        jScrollPaneForNames.setMaximumSize(new Dimension(9999999, 40));
        frame.add(jScrollPaneForNames, c);

        c.weighty = 0.0;
        c.fill = GridBagConstraints.HORIZONTAL;
        controlPanel.setMinimumSize(new Dimension(1, 80));
        frame.add(controlPanel, c);

        table.setHorizontalScrollEnabled(true);
        table.updateFilteringTableSetup();

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        frame.setSize((int) (0.67 * width), height / 2);
        frame.setLocation((int) (0.33 * width), height / 2);
        frame.setVisible(true);
    }

    if ((tableUpdateThread == null) || (!tableUpdateThread.isAlive())) {
        tableUpdateThread = new Thread(() -> {
            try {
                checkForDirtiness();
            } catch (Exception e) {
                Utils.log("Exception in ListOfPointsView GUI update thread", LogLevel.ERROR);
                Utils.printStack(e);
            }
        }, "ListOfPointsView GUI update thread");

        tableUpdateThread.start();
    }
}

From source file:org.openmicroscopy.shoola.agents.treeviewer.view.ToolBar.java

/**
 * Creates the menu hosting the users belonging to the specified group.
 * Returns <code>true</code> if the group is selected, <code>false</code>
 * otherwise./* w ww . jav  a 2  s . c om*/
 * 
 * @param groupItem The item hosting the group.
 * @param size The number of groups.
 * @return See above.
 */
private boolean createGroupMenu(GroupItem groupItem, int size) {
    long loggedUserID = model.getUserDetails().getId();
    GroupData group = groupItem.getGroup();
    //Determine the user already added to the display
    Browser browser = model.getBrowser(Browser.PROJECTS_EXPLORER);
    TreeImageDisplay refNode = null;
    List<TreeImageDisplay> nodes;
    ExperimenterVisitor visitor;
    List<Long> users = new ArrayList<Long>();
    //Find the group already displayed
    if (group != null && size > 0) {
        visitor = new ExperimenterVisitor(browser, group.getId());
        browser.accept(visitor);
        nodes = visitor.getNodes();
        if (nodes.size() == 1) {
            refNode = nodes.get(0);
        }
        visitor = new ExperimenterVisitor(browser, -1, -1);
        if (refNode != null)
            refNode.accept(visitor);
        else if (size == 1)
            browser.accept(visitor);
        nodes = visitor.getNodes();

        TreeImageDisplay n;
        if (CollectionUtils.isNotEmpty(nodes)) {
            Iterator<TreeImageDisplay> j = nodes.iterator();
            while (j.hasNext()) {
                n = j.next();
                if (n.getUserObject() instanceof ExperimenterData) {
                    users.add(((ExperimenterData) n.getUserObject()).getId());
                }
            }
            if (size == 1) {
                groupItem.setMenuSelected(true, false);
            }
        }
    }

    //now add the users
    List<DataMenuItem> items = new ArrayList<DataMenuItem>();
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    List l = null;
    if (group != null)
        l = sorter.sort(group.getLeaders());
    Iterator i;
    ExperimenterData exp;

    DataMenuItem item, allUser;
    JPanel list;

    boolean view = true;
    if (group != null) {
        int level = group.getPermissions().getPermissionsLevel();
        if (level == GroupData.PERMISSIONS_PRIVATE) {
            view = model.isAdministrator() || model.isGroupOwner(group);
        }
    }

    list = new JPanel();
    list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
    allUser = new DataMenuItem(DataMenuItem.ALL_USERS_TEXT, true);
    items.add(allUser);
    if (view)
        list.add(allUser);
    p.add(UIUtilities.buildComponentPanel(list));
    int count = 0;
    int total = 0;
    if (CollectionUtils.isNotEmpty(l)) {
        total += l.size();
        i = l.iterator();
        list = new JPanel();
        list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
        while (i.hasNext()) {
            exp = (ExperimenterData) i.next();
            if (view || exp.getId() == loggedUserID) {
                item = new DataMenuItem(exp, true);
                item.setSelected(users.contains(exp.getId()));
                if (item.isSelected())
                    count++;
                item.addPropertyChangeListener(groupItem);
                items.add(item);
                list.add(item);
            }
        }
        if (list.getComponentCount() > 0) {
            p.add(formatHeader("Group owners"));
            p.add(UIUtilities.buildComponentPanel(list));
        }
    }

    if (group != null)
        l = sorter.sort(group.getMembersOnly());
    if (CollectionUtils.isNotEmpty(l)) {
        total += l.size();
        i = l.iterator();
        list = new JPanel();
        list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
        while (i.hasNext()) {
            exp = (ExperimenterData) i.next();
            if (view || exp.getId() == loggedUserID) {
                item = new DataMenuItem(exp, true);
                item.setSelected(users.contains(exp.getId()));
                if (item.isSelected())
                    count++;
                item.addPropertyChangeListener(groupItem);
                items.add(item);
                list.add(item);
            }
        }
        if (list.getComponentCount() > 0) {
            p.add(formatHeader("Members"));
            p.add(UIUtilities.buildComponentPanel(list));
        }
    }
    allUser.setSelected(total != 0 && total == count);
    allUser.addPropertyChangeListener(groupItem);
    JScrollPane pane = new JScrollPane(p);
    Dimension d = p.getPreferredSize();
    int max = 500;
    if (d.height > max) {
        Insets insets = pane.getInsets();
        pane.setPreferredSize(new Dimension(d.width + insets.left + insets.right + 20, max));
    }

    groupItem.add(pane);
    groupItem.setUsersItem(items);
    groupItem.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            String name = evt.getPropertyName();
            if (GroupItem.USER_SELECTION_PROPERTY.equals(name))
                handleSelection();
            else if (GroupItem.ALL_GROUPS_SELECTION_PROPERTY.equals(name))
                handleAllGroupsSelection(true);
            else if (GroupItem.ALL_GROUPS_DESELECTION_PROPERTY.equals(name))
                handleAllGroupsSelection(false);
            else if (GroupItem.ALL_USERS_SELECTION_PROPERTY.equals(name))
                handleAllUsersSelection((Boolean) evt.getNewValue());
        }
    });
    return groupItem.isMenuSelected();
}

From source file:Citas.FrameCita.java

public FrameCita()
        throws ClientProtocolException, IOException, JSONException, ParseException, java.text.ParseException {

    initComponents();/* w  w w  .j a v a  2  s. co  m*/
    this.getContentPane().setLayout(new GridBagLayout());
    rutasLeer = new Leer();
    rutasAdd = new Add();
    medico = new Medico(2, 0, 3, 30); //MEDICO EN SESIOOON
    citas = new Citas[medico.cantidadDeCitasxDia(10, 30)];

    try {
        font = Font.createFont(Font.TRUETYPE_FONT, new File("Sertig.otf"));
        font = font.deriveFont(Font.BOLD, 11);
    } catch (FontFormatException ex) {
        Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
    }

    setTitle("Citas");

    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weightx = 0.5;
    gbc.weighty = 0.5;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.fill = GridBagConstraints.BOTH;
    this.getContentPane().add(PanelCalendar, gbc);
    gbc.weightx = 0.0;
    gbc.weighty = 0.0;

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weightx = 0.5;
    gbc.weighty = 1.0;
    this.getContentPane().add(PanelCita, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    gbc.gridheight = 2;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    this.getContentPane().add(PanelDetalle, gbc);

    ////////////////// PANEL DETALLES

    //Colores
    colorBackGround = new Color(hex("8FA8F6"));//Color de los BackGround 
    colorTextFields = new Color(hex("CDCBA6"));//Color de los JTextFields
    colorDelPapa = new Color(hex("2980b9"));//Color del backgorud del papa
    colorBotones = new Color(hex("2C3E50"));//Color d elos botonte
    colorActivo = new Color(hex("81CFE0"));//Color de los jTextFild cuando los activan
    //Colores

    //Inicializaciones

    this.setBackground(colorDelPapa);//Color del backgroud
    //BOTONES INICIALIZACION
    modificarB = new JButton("Modificar");
    eliminarB = new JButton("Eliminar");
    agregarB = new JButton("Agregar");
    atrasB = new JButton("Atras");
    buscarB = new JButton("Buscar");
    Botones = new JPanel(); //PAnel donde van los botones Agregar, Modificar y Eliminar
    BotonAtras = new JPanel(); //PAnel donde va el boton atras
    BotonBuscar = new JPanel(); //PAnel donde va el boton buscar
    agregarB.addActionListener(this);
    modificarB.addActionListener(this);
    eliminarB.addActionListener(this);
    atrasB.addActionListener(this);
    buscarB.addActionListener(this);
    // FIN BOTONES INICIALIZACION

    PanelCita.setLayout(new GridBagLayout());

    disenoBotones(modificarB);
    disenoBotones(eliminarB);
    disenoBotones(agregarB);
    disenoBotones(atrasB);
    disenoBotones(buscarB);
    PanelDetalle.setLayout(new GridBagLayout()); //Panel Pap (PanelDetalle)
    cambiarColorPanel(PanelCalendar, colorDelPapa);
    cambiarColorPanel(PanelCita, colorDelPapa);
    cambiarColorPanel(PanelDetalle, colorDelPapa);

    //LABELS
    horaCitas = new JLabel();
    fechaL = new JLabel("<HTML> Fecha &nbsp</HTML>");
    horaL = new JLabel("<HTML> Hora &nbsp</HTML>");
    nombreL = new JLabel("<HTML> Nombre &nbsp &nbsp </HTML>");
    apellidoL = new JLabel("<HTML> Apellido &nbsp &nbsp &nbsp</HTML>");
    cedulaL = new JLabel("<HTML> Cedula &nbsp &nbsp &nbsp &nbsp &nbsp</HTML>");
    direccionL = new JLabel("<HTML> Direccion &nbsp &nbsp</HTML>");
    motivosL = new JLabel("<HTML> Motivos &nbsp &nbsp &nbsp &nbsp</HTML>");
    telefonoCasaL = new JLabel("<HTML> Tlfn Casa&nbsp </HTML>");
    telefonoCelularL = new JLabel("<HTML> Tlfn Celular</HTML>");
    correoL = new JLabel("<HTML> Correo &nbsp &nbsp &nbsp</HTML>");

    font = font = font.deriveFont(Font.BOLD, 11);
    disenoLabel(horaCitas);
    disenoLabel(fechaL);
    disenoLabel(horaL);
    disenoLabel(nombreL);
    disenoLabel(apellidoL);
    disenoLabel(cedulaL);
    disenoLabel(direccionL);
    disenoLabel(motivosL);
    disenoLabel(telefonoCasaL);
    disenoLabel(telefonoCelularL);
    disenoLabel(correoL);

    //JTEXTFIELDS y TEXAREA

    fechaJ = new JTextField("");
    horaJ = new JTextField("");
    nombreJ = new JTextField("");
    apellidoJ = new JTextField("");
    cedulaJ = new JTextField("");
    direccionJ = new JTextField();
    motivosTA = new JTextArea("");
    telefonoCasaJ = new JTextField("");
    telefonoCelularJ = new JTextField("");
    correoJ = new JTextField("");
    //COLORES
    /*fechaJ.setBackground(colorTextFields);
    horaJ.setBackground(colorTextFields);
    nombreJ.setBackground(colorTextFields);
    apellidoJ.setBackground(colorTextFields);
    cedulaJ.setBackground(colorTextFields);
    direccionJ.setBackground(colorTextFields);
    motivosTA .setBackground(colorTextFields);
    telefonoCasaJ.setBackground(colorTextFields);
    telefonoCelularJ.setBackground(colorTextFields);
    correoJ.setBackground(colorTextFields);
    */
    //Aadir componentes al PanelDetalle
    GridBagConstraints constraints = new GridBagConstraints();

    //Caracteristicas globales del grid
    constraints.fill = GridBagConstraints.BOTH;
    constraints.weighty = 1.0;
    constraints.insets.set(5, 0, 5, 10);
    //Fin Caracteristicas Globales del grid

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(fechaL, constraints);

    constraints.gridx = 1; //Necesita estirarse
    constraints.gridy = 0;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(fechaJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(horaL, constraints);

    constraints.gridx = 1; //Necesita estirarse
    constraints.gridy = 1;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(horaJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 2;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(nombreL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 2;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(nombreJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 3;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(apellidoL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 3;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(apellidoJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 4;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(cedulaL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 4;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(cedulaJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 5;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(direccionL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 5;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(direccionJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 6;
    constraints.gridwidth = 1;
    constraints.gridheight = 2;
    constraints.weighty = 1.0;
    PanelDetalle.add(motivosL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 6;
    constraints.gridwidth = 1;
    constraints.gridheight = 2;
    constraints.weightx = 1.0;
    constraints.weighty = 1.0;
    PanelDetalle.add(motivosTA, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 8;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(telefonoCasaL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 8;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(telefonoCasaJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 9;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(telefonoCelularL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 9;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(telefonoCelularJ, constraints);
    constraints.weightx = 0.0;

    constraints.gridx = 0;
    constraints.gridy = 10;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    PanelDetalle.add(correoL, constraints);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 10;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1.0;
    PanelDetalle.add(correoJ, constraints);
    constraints.weightx = 0.0;

    //PANEL DE LOS BOTONES

    constraints.insets.set(30, 0, 10, 10);

    constraints.gridx = 1;//Necesita estirarse
    constraints.gridy = 11;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 0.0;
    FlowLayout flowLayout1 = new FlowLayout();
    Botones.setLayout(flowLayout1);
    Botones.add(agregarB);
    Botones.add(modificarB);
    Botones.add(eliminarB);
    PanelDetalle.add(Botones, constraints);

    //Boton Buscar
    constraints.anchor = GridBagConstraints.NORTH;
    constraints.insets.set(10, 0, 0, 0);
    constraints.gridx = 2;//Necesita estirarse
    constraints.gridy = 4;
    constraints.gridwidth = 1;
    constraints.gridheight = 0;
    constraints.weightx = 0.0;
    BotonBuscar.setLayout(flowLayout1);
    BotonBuscar.add(buscarB);
    BotonBuscar.setBackground(colorBackGround);
    PanelDetalle.add(BotonBuscar, constraints);
    constraints.insets.set(30, 0, 10, 10);

    //BOTON ATRAS

    constraints.insets.set(30, 0, 10, 10);
    constraints.gridx = 2;//Necesita estirarse
    constraints.gridy = 11;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 0.0;

    BotonAtras.setLayout(flowLayout1);
    BotonAtras.add(atrasB);

    PanelDetalle.add(BotonAtras, constraints);

    cambiarColorPanel(Botones, colorDelPapa);
    cambiarColorPanel(BotonBuscar, colorDelPapa);
    cambiarColorPanel(BotonAtras, colorDelPapa);

    PanelDetalle.setVisible(true);

    //////////////////////ULTIMAS MOTIFICACIONES PRIMER INCREMENTO
    atrasB.setEnabled(false);
    buscarB.setEnabled(false);
    modificarB.setEnabled(false);
    agregarB.setEnabled(false);
    eliminarB.setEnabled(false);
    fechaJ.setEditable(false);
    horaJ.setEditable(false);
    nombreJ.setEditable(false);
    apellidoJ.setEditable(false);
    cedulaJ.setEditable(false);
    direccionJ.setEditable(false);
    motivosTA.setEditable(false);
    telefonoCasaJ.setEditable(false);
    telefonoCelularJ.setEditable(false);
    correoJ.setEditable(false);

    /////////////////////FIN ULTIMAS MOTIFICACIONES PRIMER INCREMENTO

    /////////////////Para enero

    setCitas();
    dibujarPanelCita(medico);//Dibuja la "libreta" de las citas

    /////// fin para ENERO

    //jCalendar1.getDayChooser().addDateEvaluator(new DJFechasEspInv());//Pinta las Fechas ocupadas en rojo
    jCalendar1.addPropertyChangeListener("calendar", new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            try {
                try {
                    setCitas();
                } catch (ClientProtocolException ex) {
                    Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
                } catch (java.text.ParseException ex) {
                    Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(FrameCita.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

}

From source file:edu.ku.brc.specify.tasks.CleanupToolsTask.java

/**
 * /*  w w  w .  j a  va 2 s. c  o  m*/
 */
private void updateNames(final Vector<AgentNameCleanupParserDlg.DataItem> dataItemsList) {
    final String PRC = "PROCESS";
    final SimpleGlassPane glassPane = UIRegistry.writeSimpleGlassPaneMsg("Processing agents...", 24);

    //prgDlg = new ProgressDialog(getResourceString("CLNUP_AG_PRG_TITLE"), true, false);
    //prgDlg.getProcessProgress().setIndeterminate(true);
    //prgDlg.setDesc(getResourceString("CLNUP_AG_INIT_MSG"));
    //UIHelper.centerAndShow(prgDlg);

    final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        double tot = 0; // 1 -> 100
        double step = 1.0;
        int cnt = 0;

        @Override
        protected Object doInBackground() throws Exception {
            step = 100.0 / dataItemsList.size();

            Connection conn = null;
            PreparedStatement pStmt = null;
            try {
                String sql = "UPDATE agent SET LastName=?, FirstName=?,MiddleInitial=? WHERE AgentID = ?";
                conn = DBConnection.getInstance().createConnection();
                pStmt = conn.prepareStatement(sql);

                for (DataItem di : dataItemsList) {
                    if (di.isIncluded()) {
                        setColumn(pStmt, 1, di.getLastName());
                        setColumn(pStmt, 2, di.getFirstName());
                        setColumn(pStmt, 3, di.getMidName());
                        pStmt.setInt(4, di.getAgentId());

                        if (pStmt.executeUpdate() != 1) {
                            log.error(String.format("Error updating AgentID %d", di.getAgentId()));
                        }
                    }

                    tot += step;
                    if (((int) tot) > cnt) {
                        cnt = (int) tot;
                        firePropertyChange(PRC, -1, cnt);
                    }
                }
                dataItemsList.clear();

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (pStmt != null)
                        pStmt.close();
                    if (conn != null)
                        conn.close();

                } catch (SQLException ex) {
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.showLocalizedMsg("Done.");
        }
    };
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (PRC.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });
    worker.execute();
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaToolsDlg.java

/**
 * /*  w  w w  .  j a  v  a 2s  . c o m*/
 */
@SuppressWarnings("unchecked")
protected void exportSchemaLocales() {
    FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()), getResourceString("Save"),
            FileDialog.SAVE);
    dlg.setVisible(true);

    String fileName = dlg.getFile();
    if (fileName != null) {
        final File outFile = new File(dlg.getDirectory() + File.separator + fileName);
        //final File    outFile = new File("xxx.xml");

        final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SL_EXPORT_SCHEMA"), 18);
        glassPane.setBarHeight(12);
        glassPane.setFillColor(new Color(0, 0, 0, 85));

        setGlassPane(glassPane);
        glassPane.setVisible(true);

        SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
            @Override
            protected Integer doInBackground() throws Exception {

                DataProviderSessionIFace session = null;
                try {
                    session = DataProviderFactory.getInstance().createSession();

                    int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
                    String sql = String.format(
                            "FROM SpLocaleContainer WHERE disciplineId = %d AND schemaType = %d", dispId,
                            schemaType);
                    List<SpLocaleContainer> spContainers = (List<SpLocaleContainer>) session.getDataList(sql);
                    try {
                        FileWriter fw = new FileWriter(outFile);

                        //fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vector>\n");
                        fw.write("<vector>\n");

                        BeanWriter beanWriter = new BeanWriter(fw);
                        XMLIntrospector introspector = beanWriter.getXMLIntrospector();
                        introspector.getConfiguration().setWrapCollectionsInElement(true);
                        beanWriter.getBindingConfiguration().setMapIDs(false);
                        beanWriter.setWriteEmptyElements(false);

                        beanWriter.enablePrettyPrint();

                        double step = 100.0 / (double) spContainers.size();
                        double total = 0.0;
                        for (SpLocaleContainer container : spContainers) {
                            // force Load of lazy collections
                            container.getDescs().size();
                            container.getNames().size();

                            // Leaving this Code as an example of specifying the bewtixt file.
                            /*InputStream inputStream = Specify.class.getResourceAsStream("datamodel/SpLocaleContainer.betwixt");
                            //InputStream inputStream = Specify.class.getResourceAsStream("/edu/ku/brc/specify/tools/schemalocale/SpLocaleContainer.betwixt");
                            InputSource inputSrc    = new InputSource(inputStream); 
                            beanWriter.write(container, inputSrc);
                            inputStream.close(); */

                            beanWriter.write(container);

                            total += step;
                            firePropertyChange("progress", 0, (int) total);
                        }

                        fw.write("</vector>\n");
                        fw.close();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                } catch (Exception e) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e);
                    e.printStackTrace();

                } finally {
                    if (session != null) {
                        session.close();
                    }
                }

                return null;
            }

            @Override
            protected void done() {
                super.done();

                glassPane.setVisible(false);
            }
        };

        backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                }
            }
        });
        backupWorker.execute();
    }
}

From source file:org.openconcerto.sql.model.SQLDataSource.java

private SQLDataSource(DBSystemRoot sysRoot) {
    this.sysRoot = sysRoot;
    // on a besoin d'une implementation synchronise
    this.handlers = new Hashtable<Thread, HandlersStack>();
    // weak, since this is only a hint to avoid initializing the connection
    // on each borrowal
    this.schemaUptodate = new WeakHashMap<Connection, Object>();
    this.uptodate = new WeakHashMap<Connection, Object>();
    this.initialShemaSet = false;
    this.initialShema = null;

    // see #getNewConnection(boolean)
    this.setValidationQuery("SELECT 1");
    this.setTestOnBorrow(false);

    this.setInitialSize(3);
    this.setMaxActive(48);
    // creating connections is quite costly so make sure we always have a couple free
    this.setMinIdle(2);
    // but not too much as it can lock out other users (the server has a max connection count)
    this.setMaxIdle(16);
    this.setBlockWhenExhausted(false);
    // check 5 connections every 4 seconds
    this.setTimeBetweenEvictionRunsMillis(4000);
    this.setNumTestsPerEvictionRun(5);
    // kill extra (above minIdle) connections after 40s
    this.setSoftMinEvictableIdleTimeMillis(TimeUnit.SECONDS.toMillis(40));
    // kill idle connections after 30 minutes (even if it means re-creating some new ones
    // immediately afterwards to ensure minIdle connections)
    this.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(30));

    // the default of many systems
    this.txIsolation = Connection.TRANSACTION_READ_COMMITTED;
    // by definition unknown without a connection
    this.dbTxIsolation = null;
    // it's rare that DB configuration changes, and it's expensive to add a trip to the server
    // for each new connection
    this.checkOnceDBTxIsolation = true;

    // see #createDataSource() for properties not supported by this class
    this.tables = Collections.emptySet();
    this.descL = new PropertyChangeListener() {
        @Override//from   w ww . j a v  a 2s  .c o m
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("descendants")) {
                // the dataSource must always have all tables, to listen to them for its cache
                setTables(((DBSystemRoot) evt.getSource()).getDescs(SQLTable.class));
            }
        }
    };
    this.sysRoot.addListener(this.descL);
    this.cache = null;
    this.cacheEnabled = false;
}