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:net.cantab.hayward.george.OCS.Statics.java

/**
 * Create all the objects which are going to hang off the task bar here.
 *
 * @param parent/* w  w  w . ja v a2  s. c o m*/
 */
public void addTo(Buildable parent) {
    if (parent instanceof ToolBarComponent) {
        toolbar = ((ToolBarComponent) parent).getToolBar();
        createNormalEntries();
        createDebugEntries();
    }
    /*
     * Add this object to lists of those which encode/decode commands and
     * to list of those that save game information
     */
    GameModule.getGameModule().addCommandEncoder(this);
    GameModule.getGameModule().getGameState().addGameComponent(this);
    /*
     * Create the preferences in case they don't exist
     */
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new BooleanConfigurer(HIDDEN_MOVEMENT_OFF, "OCS - Disable all Fog Of War", Boolean.FALSE));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new StringEnumConfigurer(ZONE_SECURITY, "OCS - Display of pieces in off-map boxes",
                    new String[] { "Visible", "Masked", "Invisible" }));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new BooleanConfigurer(RANGE_IN_USE, "OCS - Enable range based extra Fog Of War", Boolean.FALSE));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"), new IntConfigurer(
            RANGE_AIR_HIDDEN, "OCS - Range at which air units become invisible", new Integer(40)));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"), new IntConfigurer(
            RANGE_HIDDEN, "OCS - Range at which land/sea units become invisible", new Integer(20)));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new IntConfigurer(RANGE_CONCEALED, "OCS - Range at which units become masked", new Integer(10)));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"), new IntConfigurer(
            RANGE_FLAT, "OCS - Range at which stacks are shown as a single counter", new Integer(5)));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new BooleanConfigurer(USE_FORMATIONS, "OCS - Enable Formation Markers as in 13.7", Boolean.FALSE));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new BooleanConfigurer(HEX_RANGES, "OCS - Range Options use hexes rather than radii",
                    Boolean.FALSE));
    GameModule.getGameModule().getPrefs().addOption(Resources.getString("Prefs.general_tab"),
            new BooleanConfigurer(USE_NEAREST_AEP, "OCS - Use nearest AEP (rather than minimal distance)",
                    Boolean.FALSE));
    /*
     * Listen for chnages to user name / password
     */
    GameModule.getGameModule().getPrefs().getOption(GameModule.REAL_NAME)
            .addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    userIdChanged();
                }
            });
    GameModule.getGameModule().getPrefs().getOption(GameModule.SECRET_NAME)
            .addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    userIdChanged();
                }
            });
    /*
     * Get the main map
     */
    List<Map> a = GameModule.getGameModule().getAllDescendantComponentsOf(Map.class);
    theMap = a.get(0);
    /*
     * Get the hex size from the main map
     */
    List<BoardPicker> b = theMap.getAllDescendantComponentsOf(BoardPicker.class);
    if (!b.isEmpty()) {
        BoardPicker c = b.get(0);
        String[] boards = c.getAllowableBoardNames();
        if (boards.length != 0) {
            Board d = c.getBoard(boards[0]);
            List<HexGrid> e = d.getAllDescendantComponentsOf(HexGrid.class);
            if (!e.isEmpty()) {
                HexGrid h = e.get(0);
                hexSize = h.getDy();
            }
        }
    }
}

From source file:gda.gui.BatonPanel.java

JBatonDialog(Frame aFrame, String title, boolean modal, BatonPanel panel) {
    super(aFrame, title, modal);
    setContentPane(panel);/*from   ww w  .  j a va2s .c o m*/
    pack();
    InterfaceProvider.getBatonStateProvider().addBatonChangedObserver(this);
    addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            setVisible(false);
        }

    });
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

public boolean doRestoreBulkDataInBackground(final String databaseName, final String options,
        final String restoreZipFilePath, final SimpleGlassPane glassPane, final String completionMsgKey,
        final PropertyChangeListener pcl, final boolean doSynchronously, final boolean doDropDatabase) {
    getNumberofTables();/* www .ja v a 2  s  .  com*/

    SynchronousWorker backupWorker = new SynchronousWorker() {
        long dspMegs = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            boolean skipTrackExceptions = BasicSQLUtils.isSkipTrackExceptions();
            BasicSQLUtils.setSkipTrackExceptions(false);
            try {
                String userName = itUsername != null ? itUsername : DBConnection.getInstance().getUserName();
                String password = itPassword != null ? itPassword : DBConnection.getInstance().getPassword();

                DBConnection currDBConn = DBConnection.getInstance();
                String dbName = currDBConn.getDatabaseName();
                DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
                if (dbMgr != null) {
                    boolean isConnected = dbMgr.connectToDBMS(userName, password, currDBConn.getServerName(),
                            dbName, currDBConn.isEmbedded());
                    if (isConnected) {
                        if (doDropDatabase) {
                            if (dbMgr.doesDBExists(databaseName) && !dbMgr.dropDatabase(databaseName)) {
                                log.error("Database[" + databaseName + "] could not be dropped before load.");
                                UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DB", databaseName);
                                return null;
                            }

                            if (!dbMgr.createDatabase(databaseName)) {
                                log.error("Database[" + databaseName + "] could not be created before load.");
                                UIRegistry.showLocalizedError("MySQLBackupService.CRE_DRP_DB", databaseName);
                                return null;
                            }
                        }

                        DatabaseDriverInfo driverInfo = DatabaseDriverInfo
                                .getDriver(DBConnection.getInstance().getDriverName());
                        String connStr = DBConnection.getInstance().getConnectionStr();

                        DBConnection itDBConn = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                driverInfo.getDialectClassName(), databaseName, connStr, userName, password);
                        Connection connection = itDBConn.createConnection();
                        connection.setCatalog(databaseName);

                        List<File> unzippedFiles = ZipFileHelper.getInstance()
                                .unzipToFiles(new File(restoreZipFilePath));

                        boolean dbCreated = false;
                        for (File file : unzippedFiles) {
                            //System.out.println(file.getName());
                            if (file.getName().equals("createdb.sql")) {
                                long size = restoreFile(connection, file);
                                log.debug("size: " + size);
                                dbCreated = true;
                            }
                        }

                        if (dbCreated) {
                            for (File file : unzippedFiles) {
                                if (file.getName().endsWith("infile")) {
                                    String fPath = file.getCanonicalPath();
                                    if (UIHelper.isWindows()) {
                                        fPath = StringUtils.replace(fPath, "\\", "\\\\");
                                    }
                                    String sql = "LOAD DATA LOCAL INFILE '" + fPath + "' INTO TABLE "
                                            + FilenameUtils.getBaseName(file.getName());
                                    log.debug(sql);
                                    //System.err.println(sql);
                                    int rv = BasicSQLUtils.update(connection, sql);
                                    log.debug("done fPath[" + fPath + "] rv= " + rv);
                                    //System.err.println("done fPath["+fPath+"] rv= "+rv);
                                }
                            }
                        }

                        ZipFileHelper.getInstance().cleanUp();

                        /*if (!dbMgr.dropDatabase(databaseName))
                        {
                        log.error("Database["+databaseName+"] could not be dropped after load.");
                        UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DBAF", databaseName);
                        }*/

                        setProgress(100);

                        //errorMsg = sb.toString();

                        itDBConn.close();
                    } else {
                        // error can't connect
                    }
                } else {
                    // error
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                errorMsg = ex.toString();
                if (pcl != null) {
                    pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
                }

            } finally {
                BasicSQLUtils.setSkipTrackExceptions(skipTrackExceptions);
            }
            return null;
        }

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

            JStatusBar statusBar = UIRegistry.getStatusBar();
            if (statusBar != null) {
                statusBar.setProgressDone(STATUSBAR_NAME);
            }

            if (glassPane != null) {
                UIRegistry.clearSimpleGlassPaneMsg();
            }

            if (StringUtils.isNotEmpty(errorMsg)) {
                UIRegistry.showError(errorMsg);
            }

            if (statusBar != null) {
                statusBar.setText(UIRegistry.getLocalizedMessage(completionMsgKey, dspMegs));
            }

            if (pcl != null) {
                pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, 0, 1));
            }
        }
    };

    if (glassPane != null) {
        glassPane.setProgress(0);
    }

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName()) && glassPane != null) {
                int value = (Integer) evt.getNewValue();

                if (value < 100) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                } else {
                    glassPane.setProgress(100);
                }
            }
        }
    });

    if (doSynchronously) {
        return backupWorker.doWork();
    }

    backupWorker.execute();
    return true;
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Activates itself as a viewer by configuring Size, and location of itself,
 * and configures the default Tabbed Pane elements with the correct layout,
 * table columns, and sets itself viewable.
 *///from  w ww.  ja v  a2 s  .  c o  m
public void activateViewer() {
    LoggerRepository repo = LogManager.getLoggerRepository();
    if (repo instanceof LoggerRepositoryEx) {
        this.pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
    }
    initGUI();

    initPrefModelListeners();

    /**
     * We add a simple appender to the MessageCenter logger
     * so that each message is displayed in the Status bar
     */
    MessageCenter.getInstance().getLogger().addAppender(new AppenderSkeleton() {
        protected void append(LoggingEvent event) {
            getStatusBar().setMessage(event.getMessage().toString());
        }

        public void close() {
        }

        public boolean requiresLayout() {
            return false;
        }
    });

    initSocketConnectionListener();

    if (pluginRegistry.getPlugins(Receiver.class).size() == 0) {
        noReceiversDefined = true;
    }

    getFilterableColumns().add(ChainsawConstants.LEVEL_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.LOGGER_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.THREAD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NDC_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.PROPERTIES_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.CLASS_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.METHOD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.FILE_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NONE_COL_NAME);

    JPanel panePanel = new JPanel();
    panePanel.setLayout(new BorderLayout(2, 2));

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

    getTabbedPane().addChangeListener(getToolBarAndMenus());
    getTabbedPane().addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            LogPanel thisLogPanel = getCurrentLogPanel();
            if (thisLogPanel != null) {
                thisLogPanel.updateStatusBar();
            }
        }
    });

    KeyStroke ksRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksGotoLine = KeyStroke.getKeyStroke(KeyEvent.VK_G,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksRight, "MoveRight");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksLeft, "MoveLeft");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksGotoLine, "GotoLine");

    Action moveRight = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            ++temp;

            if (temp != getTabbedPane().getTabCount()) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action moveLeft = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            --temp;

            if (temp > -1) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action gotoLine = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String inputLine = JOptionPane.showInputDialog(LogUI.this, "Enter the line number to go:",
                    "Goto Line", -1);
            try {
                int lineNumber = Integer.parseInt(inputLine);
                int row = getCurrentLogPanel().setSelectedEvent(lineNumber);
                if (row == -1) {
                    JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number",
                            "Error", 0);
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number", "Error",
                        0);
            }
        }
    };

    getTabbedPane().getActionMap().put("MoveRight", moveRight);
    getTabbedPane().getActionMap().put("MoveLeft", moveLeft);
    getTabbedPane().getActionMap().put("GotoLine", gotoLine);

    /**
         * We listen for double clicks, and auto-undock currently selected Tab if
         * the mouse event location matches the currently selected tab
         */
    getTabbedPane().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            if ((e.getClickCount() > 1) && ((e.getModifiers() & InputEvent.BUTTON1_MASK) > 0)) {
                int tabIndex = getTabbedPane().getSelectedIndex();

                if ((tabIndex != -1) && (tabIndex == getTabbedPane().getSelectedIndex())) {
                    LogPanel logPanel = getCurrentLogPanel();

                    if (logPanel != null) {
                        logPanel.undock();
                    }
                }
            }
        }
    });

    panePanel.add(getTabbedPane());
    addWelcomePanel();

    getContentPane().add(toolbar, BorderLayout.NORTH);
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    mainReceiverSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panePanel, receiversPanel);
    dividerSize = mainReceiverSplitPane.getDividerSize();
    mainReceiverSplitPane.setDividerLocation(-1);

    getContentPane().add(mainReceiverSplitPane, BorderLayout.CENTER);

    /**
     * We need to make sure that all the internal GUI components have been added to the
     * JFrame so that any plugns that get activated during initPlugins(...) method
     * have access to inject menus  
     */
    initPlugins(pluginRegistry);

    mainReceiverSplitPane.setResizeWeight(1.0);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent event) {
            exit();
        }
    });
    preferencesFrame.setTitle("'Application-wide Preferences");
    preferencesFrame.setIconImage(((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
    preferencesFrame.getContentPane().add(applicationPreferenceModelPanel);

    preferencesFrame.setSize(750, 520);

    Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
    preferencesFrame.setLocation(new Point((screenDimension.width / 2) - (preferencesFrame.getSize().width / 2),
            (screenDimension.height / 2) - (preferencesFrame.getSize().height / 2)));

    pack();

    final JPopupMenu tabPopup = new JPopupMenu();
    final Action hideCurrentTabAction = new AbstractAction("Hide") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            if (selectedComp instanceof LogPanel) {
                displayPanel(getCurrentLogPanel().getIdentifier(), false);
                tbms.stateChange();
            } else {
                getTabbedPane().remove(selectedComp);
            }
        }
    };

    final Action hideOtherTabsAction = new AbstractAction("Hide Others") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            String currentName;
            if (selectedComp instanceof LogPanel) {
                currentName = getCurrentLogPanel().getIdentifier();
            } else if (selectedComp instanceof WelcomePanel) {
                currentName = ChainsawTabbedPane.WELCOME_TAB;
            } else {
                currentName = ChainsawTabbedPane.ZEROCONF;
            }

            int count = getTabbedPane().getTabCount();
            int index = 0;

            for (int i = 0; i < count; i++) {
                String name = getTabbedPane().getTitleAt(index);

                if (getPanelMap().keySet().contains(name) && !name.equals(currentName)) {
                    displayPanel(name, false);
                    tbms.stateChange();
                } else {
                    index++;
                }
            }
        }
    };

    Action showHiddenTabsAction = new AbstractAction("Show All Hidden") {
        public void actionPerformed(ActionEvent e) {
            for (Iterator iter = getPanels().entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                Boolean docked = (Boolean) entry.getValue();
                if (docked.booleanValue()) {
                    String identifier = (String) entry.getKey();
                    int count = getTabbedPane().getTabCount();
                    boolean found = false;

                    for (int i = 0; i < count; i++) {
                        String name = getTabbedPane().getTitleAt(i);

                        if (name.equals(identifier)) {
                            found = true;

                            break;
                        }
                    }

                    if (!found) {
                        displayPanel(identifier, true);
                        tbms.stateChange();
                    }
                }
            }
        }
    };

    tabPopup.add(hideCurrentTabAction);
    tabPopup.add(hideOtherTabsAction);
    tabPopup.addSeparator();
    tabPopup.add(showHiddenTabsAction);

    final PopupListener tabPopupListener = new PopupListener(tabPopup);
    getTabbedPane().addMouseListener(tabPopupListener);

    this.handler.addPropertyChangeListener("dataRate", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            double dataRate = ((Double) evt.getNewValue()).doubleValue();
            statusBar.setDataRate(dataRate);
        }
    });

    getSettingsManager().addSettingsListener(this);
    getSettingsManager().addSettingsListener(MRUFileListPreferenceSaver.getInstance());
    getSettingsManager().addSettingsListener(receiversPanel);
    try {
        //if an uncaught exception is thrown, allow the UI to continue to load
        getSettingsManager().loadSettings();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //app preferences have already been loaded (and configuration url possibly set to blank if being overridden)
    //but we need a listener so the settings will be saved on exit (added after loadsettings was called)
    getSettingsManager().addSettingsListener(new ApplicationPreferenceModelSaver(applicationPreferenceModel));

    setVisible(true);

    if (applicationPreferenceModel.isReceivers()) {
        showReceiverPanel();
    } else {
        hideReceiverPanel();
    }

    removeSplash();

    synchronized (initializationLock) {
        isGUIFullyInitialized = true;
        initializationLock.notifyAll();
    }

    if (noReceiversDefined && applicationPreferenceModel.isShowNoReceiverWarning()) {
        SwingHelper.invokeOnEDT(new Runnable() {
            public void run() {
                showReceiverConfigurationPanel();
            }
        });
    }

    Container container = tutorialFrame.getContentPane();
    final JEditorPane tutorialArea = new JEditorPane();
    tutorialArea.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    tutorialArea.setEditable(false);
    container.setLayout(new BorderLayout());

    try {
        tutorialArea.setPage(ChainsawConstants.TUTORIAL_URL);
        JTextComponentFormatter.applySystemFontAndSize(tutorialArea);

        container.add(new JScrollPane(tutorialArea), BorderLayout.CENTER);
    } catch (Exception e) {
        MessageCenter.getInstance().getLogger().error("Error occurred loading the Tutorial", e);
    }

    tutorialFrame.setIconImage(new ImageIcon(ChainsawIcons.HELP).getImage());
    tutorialFrame.setSize(new Dimension(640, 480));

    final Action startTutorial = new AbstractAction("Start Tutorial",
            new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will start 3 \"Generator\" receivers for use in the Tutorial.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Tutorial()).start();
                putValue("TutorialStarted", Boolean.TRUE);
            } else {
                putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    final Action stopTutorial = new AbstractAction("Stop Tutorial",
            new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will stop all of the \"Generator\" receivers used in the Tutorial, but leave any other Receiver untouched.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Runnable() {
                    public void run() {
                        LoggerRepository repo = LogManager.getLoggerRepository();
                        if (repo instanceof LoggerRepositoryEx) {
                            PluginRegistry pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
                            List list = pluginRegistry.getPlugins(Generator.class);

                            for (Iterator iter = list.iterator(); iter.hasNext();) {
                                Plugin plugin = (Plugin) iter.next();
                                pluginRegistry.stopPlugin(plugin.getName());
                            }
                        }
                    }
                }).start();
                setEnabled(false);
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    stopTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Removes all of the Tutorials Generator Receivers, leaving all other Receivers untouched");
    startTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Begins the Tutorial, starting up some Generator Receivers so you can see Chainsaw in action");
    stopTutorial.setEnabled(false);

    final SmallToggleButton startButton = new SmallToggleButton(startTutorial);
    PropertyChangeListener pcl = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            stopTutorial.setEnabled(((Boolean) startTutorial.getValue("TutorialStarted")).equals(Boolean.TRUE));
            startButton.setSelected(stopTutorial.isEnabled());
        }
    };

    startTutorial.addPropertyChangeListener(pcl);
    stopTutorial.addPropertyChangeListener(pcl);

    pluginRegistry.addPluginListener(new PluginListener() {
        public void pluginStarted(PluginEvent e) {
        }

        public void pluginStopped(PluginEvent e) {
            List list = pluginRegistry.getPlugins(Generator.class);

            if (list.size() == 0) {
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    });

    final SmallButton stopButton = new SmallButton(stopTutorial);

    final JToolBar tutorialToolbar = new JToolBar();
    tutorialToolbar.setFloatable(false);
    tutorialToolbar.add(startButton);
    tutorialToolbar.add(stopButton);
    container.add(tutorialToolbar, BorderLayout.NORTH);
    tutorialArea.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                if (e.getDescription().equals("StartTutorial")) {
                    startTutorial.actionPerformed(null);
                } else if (e.getDescription().equals("StopTutorial")) {
                    stopTutorial.actionPerformed(null);
                } else {
                    try {
                        tutorialArea.setPage(e.getURL());
                    } catch (IOException e1) {
                        MessageCenter.getInstance().getLogger()
                                .error("Failed to change the URL for the Tutorial", e1);
                    }
                }
            }
        }
    });

    /**
     * loads the saved tab settings and if there are hidden tabs,
     * hide those tabs out of currently loaded tabs..
     */

    if (!getTabbedPane().tabSetting.isWelcome()) {
        displayPanel(ChainsawTabbedPane.WELCOME_TAB, false);
    }
    if (!getTabbedPane().tabSetting.isZeroconf()) {
        displayPanel(ChainsawTabbedPane.ZEROCONF, false);
    }
    tbms.stateChange();

}

From source file:ca.uhn.hl7v2.testpanel.ui.conn.Hl7ConnectionPanelBackup.java

public void setConnection(AbstractConnection theConnection) {
    myConnection = theConnection;/* www .j  a v a  2  s. c  o m*/

    myHohSecurityKeyPwTextBox.setText(myConnection.getTlsKeystorePassword());
    myHohSecurityKeystoreTextbox.setText(myConnection.getTlsKeystoreLocation());
    myHohSecurityProfileKeystoreStatus.setText("");

    myCharsetCombo.setSelectedItem(theConnection.getCharSet());

    myTlsCheckbox.setSelected(theConnection.isTls());
    myHohTlsCheckbox.setSelected(theConnection.isTls());
    myCaptureByteStreamCheckbox.setSelected(theConnection.isCaptureBytes());

    myHohAuthEnabledCheckbox.setSelected(myConnection.isHohAuthenticationEnabled());
    myHohAuthUsernameTextbox.setText(myConnection.getHohAuthenticationUsername());
    myHohAuthPasswordTextbox.setText(myConnection.getHohAuthenticationPassword());

    updateCharset();

    Hl7V2EncodingTypeEnum encoding = theConnection.getEncoding();
    myEr7Radio.setSelected(encoding == Hl7V2EncodingTypeEnum.ER_7);
    myXmlRadio.setSelected(encoding == Hl7V2EncodingTypeEnum.XML);
    myHostBox.setText(theConnection.getHost());

    updatePortsUi();

    myStatusPropertyChangeListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            updateStatus();
        }
    };
    myConnection.addPropertyChangeListener(OutboundConnection.STATUS_PROPERTY, myStatusPropertyChangeListener);

    myStatusLinePropertyChangeListener = new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent theEvt) {
            updateStatus();
        }
    };
    myConnection.addPropertyChangeListener(OutboundConnection.STATUS_LINE_PROPERTY,
            myStatusLinePropertyChangeListener);

    updateStatus();

}

From source file:canreg.client.gui.dataentry.ImportView.java

/**
 *
 * @return//  ww  w .ja v  a2  s  .  c  om
 */
@Action()
public Task importAction() {
    // TODO: Add a handler for errors in the file structure...
    localSettings.setProperty("import_path", path);
    localSettings.writeSettings();
    progressBar.setStringPainted(true);
    importButton.setEnabled(false);
    // this.dispose();
    importTask = new ImportActionTask(
            org.jdesktop.application.Application.getInstance(canreg.client.CanRegClientApp.class));
    importTask.addPropertyChangeListener(new PropertyChangeListener() {

        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                progressBar.setValue((Integer) evt.getNewValue());
                progressBar.setString(evt.getNewValue().toString() + "%");
            } else if ("finished".equals(evt.getPropertyName())) {
                dispose();
            }
        }
    });
    return importTask;
}

From source file:ru.goodfil.catalog.ui.forms.CarsPanel.java

private void miExportToExcelActionPerformed(ActionEvent e) {
    if (listsPopupMenu.getInvoker() == vechicleTypesList || listsPopupMenu.getInvoker() == manufactorsList
            || listsPopupMenu.getInvoker() == seriesList) {

        ExportWindow exportWindow = new ExportWindow();
        exportWindow.setVisible(true);//from  w ww . ja va  2  s  .  c o m
        if (exportWindow.getDialogResult() == DialogResult.OK) {
            final ProgressMonitor progressMonitor = new ProgressMonitor(this, " ",
                    ", ??  ", 0, 100);
            progressMonitor.setProgress(0);
            progressMonitor.setMillisToPopup(0);
            progressMonitor.setMillisToDecideToPopup(0);

            FullCatalogExportTask task = new FullCatalogExportTask(exportWindow.getExportParams(),
                    listsPopupMenu.getInvoker());
            task.addPropertyChangeListener(new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("progress")) {
                        progressMonitor.setProgress(new Integer(evt.getNewValue().toString()));
                    }
                }
            });
            task.execute();
        }
    }
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testPropertyChange() throws Exception {
    final Exchanger<Boolean> boolExchanger = 
        new Exchanger<Boolean>();
    final SwingWorker<?,?> test = 
        new SwingWorker<Object, Object>() {
            @Override//from  w w  w  .  ja va2 s  .  c  o m
            protected Object doInBackground() throws Exception {
                firePropertyChange("test", null, "test");
                return null;
            }
        };
    test.addPropertyChangeListener(
        new PropertyChangeListener() {
            boolean isOnEDT = true;

            public  void propertyChange(PropertyChangeEvent evt) {
                isOnEDT &= SwingUtilities.isEventDispatchThread();
                if ("state".equals(evt.getPropertyName())
                    && StateValue.DONE == evt.getNewValue()) {
                    try {
                        boolExchanger.exchange(isOnEDT);
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
        });
    test.execute();
    assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java

/**
 * // w  w w  .java 2s .  co m
 */
public void doCreateBatchOfColObj(final Pair<String, String> catNumPair) {
    if (catNumPair.getFirst().equals(catNumPair.getSecond())) {
        return;
    }

    DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId())
            .getFieldByColumnName("CatalogNumber");
    final UIFieldFormatterIFace formatter = CatNumFld.getFormatter();
    if (!formatter.isIncrementer()) {
        //XXX this will have been checked earlier, right?
        UIRegistry.showLocalizedError(NonIncrementingCatNum);
        return;
    }

    final Vector<String> nums = new Vector<String>();
    processBatchContents(catNumPair, false, false, nums);
    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        private Vector<Pair<Integer, String>> objectsAdded = new Vector<Pair<Integer, String>>();
        private Vector<String> objectsNotAdded = new Vector<String>();
        private RecordSet batchRS;
        //private boolean invalidEntry = false;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {

            String catNum = catNumPair.getFirst();
            Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId();
            String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = "
                    + collId + " and CatalogNumber = '";
            objectsAdded.add(new Pair<Integer, String>(
                    (Integer) BasicSQLUtils.querySingleObj(coIdSql + catNum + "'"), catNum));

            int cnt = 0;
            CollectionObject co = null;
            //CollectionObject carryForwardCo = (CollectionObject )formViewObj.getDataObj();
            CollectionObject carryForwardCo;
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            try {
                carryForwardCo = session.get(CollectionObject.class,
                        ((CollectionObject) formViewObj.getDataObj()).getId());
            } finally {
                session.close();
            }

            Thread.sleep(666); //Perhaps this is unnecessary, but it seems
            //to prevent sporadic "illegal access to loading collection" hibernate errors.
            try {
                for (String currentCat : nums) {
                    try {
                        co = new CollectionObject();
                        co.initialize();

                        //Collection doesn't get set in co.initialize(), or carryForward, but it needs to be set.
                        co.setCollection(AppContextMgr.getInstance().getClassObject(Collection.class));
                        //ditto, but doesn't so much need to be set
                        co.setModifiedByAgent(carryForwardCo.getModifiedByAgent());

                        co.setCatalogNumber(currentCat);
                        formViewObj.setNewObject(co);

                        if (formViewObj.saveObject()) {
                            objectsAdded.add(new Pair<Integer, String>(
                                    (Integer) BasicSQLUtils
                                            .querySingleObj(coIdSql + co.getCatalogNumber() + "'"),
                                    co.getCatalogNumber()));
                        } else {
                            objectsNotAdded.add(formatter.formatToUI(co.getCatalogNumber()).toString());
                        }
                    } catch (Exception ex) {
                        log.error(ex);
                        objectsNotAdded.add(formatter.formatToUI(currentCat) + ": "
                                + (ex.getLocalizedMessage() == null ? "" : ex.getLocalizedMessage()));
                    }
                    cnt++;
                    firePropertyChange(GLASSKEY, 0, cnt);
                }
                firePropertyChange(GLASSKEY, 0, nums.size());

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex);
            }
            formViewObj.setDataObj(carryForwardCo);
            saveBatchObjectsToRS();
            return objectsAdded.size();
        }

        /**
         * Save the objects added to a Recordset
         */
        protected void saveBatchObjectsToRS() {
            batchRS = new RecordSet();
            batchRS.initialize();
            batchRS.setDbTableId(CollectionObject.getClassTableId());
            String name = getResourceString(BatchRSBaseName) + " " + formatter.formatToUI(catNumPair.getFirst())
                    + "-" + formatter.formatToUI(catNumPair.getSecond());
            if (objectsNotAdded.size() > 0) {
                name += "-" + UIRegistry.getResourceString(IncompleteSaveFlag);
            }
            batchRS.setName(name);
            for (Pair<Integer, String> obj : objectsAdded) {
                batchRS.addItem(obj.getFirst());
            }
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            boolean transOpen = false;
            try {
                BusinessRulesIFace busRule = DBTableIdMgr.getInstance().getBusinessRule(RecordSet.class);
                if (busRule != null) {
                    busRule.beforeSave(batchRS, session);
                }
                batchRS.setTimestampCreated(new Timestamp(System.currentTimeMillis()));
                batchRS.setOwner(AppContextMgr.getInstance().getClassObject(SpecifyUser.class));
                session.beginTransaction();
                transOpen = true;
                session.save(batchRS);
                if (busRule != null) {
                    if (!busRule.beforeSaveCommit(batchRS, session)) {
                        session.rollback();
                        throw new Exception("Business rules processing failed");
                    }
                }
                session.commit();
                transOpen = false;
                if (busRule != null) {
                    busRule.afterSaveCommit(batchRS, session);
                }
            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex);
                if (transOpen) {
                    session.rollback();
                }
            }
        }

        /**
         * Add the batch RS to the RecordSetTask UI
         */
        protected void addBatchRSToUI() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    CommandAction cmd = new CommandAction(RecordSetTask.RECORD_SET,
                            RecordSetTask.ADD_TO_NAV_BOX);
                    cmd.setData(batchRS);
                    CommandDispatcher.dispatch(cmd);
                }
            });
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            super.done();
            processingSeries.set(false);
            addBatchRSToUI();
            UIRegistry.clearSimpleGlassPaneMsg();
            if (objectsNotAdded.size() == 0) {
                UIRegistry.displayLocalizedStatusBarText(BatchSaveSuccess,
                        formatter.formatToUI(catNumPair.getFirst()),
                        formatter.formatToUI(catNumPair.getSecond()));
            } else {
                showBatchErrorObjects(objectsNotAdded, BatchSaveErrorsTitle, BatchSaveErrors);
            }
        }
    };

    final SimpleGlassPane gp = UIRegistry.writeSimpleGlassPaneMsg(getI10N("SAVING_BATCH"), 24);
    gp.setProgress(0);
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (GLASSKEY.equals(evt.getPropertyName())) {
                double value = (double) ((Integer) evt.getNewValue()).intValue();
                int percent = (int) (value / ((double) nums.size()) * 100.0);
                gp.setProgress(percent);

            }
        }
    });
    processingSeries.set(true);
    worker.execute();
    //        try {
    //           worker.get();
    //        } catch (Exception ex) {
    //           ex.printStackTrace();
    //        }
}

From source file:GUI.MainWindow.java

private void ImportScanScreenWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_ImportScanScreenWindowActivated

    Object obj = ImportFile.getModel().getElementAt(0);
    if (obj != null && obj instanceof ImportFile) {
        ImportFile imFile = (ImportFile) obj;
        System.out.println("Importing File: " + imFile.getAbsolutePath());
        ProgressBar.setIndeterminate(true);

        ImportScanTask ist = new ImportScanTask(ProgressBar, imFile, ImportScanScreen);
        ist.addPropertyChangeListener(new PropertyChangeListener() {
            @Override//from   w  w w .j  a  va 2 s.  co  m
            public void propertyChange(PropertyChangeEvent e) {
                if ("progress".equals(e.getPropertyName())) {
                    ProgressBar.setIndeterminate(false);
                    ProgressBar.setValue((Integer) e.getNewValue());
                    System.out.println("**: " + e.getNewValue());
                }
            }
        });
        ist.execute();

        try {
            DefaultMutableTreeNode new_root = ist.get();
            System.out.println("Import Finished");
            DefaultMutableTreeNode existing_root = (DefaultMutableTreeNode) VulnTree.getModel().getRoot();
            if (existing_root.getChildCount() == 0) {
                // The tree was empty so simply set the importe one into the model
                VulnTree.setModel(new DefaultTreeModel(new_root));
            } else {
                // The tree had existing children so we need to merge them
                VulnTree.setModel(new DefaultTreeModel(new TreeUtils().mergeTrees(existing_root, new_root)));
            }

        } catch (InterruptedException ex) {
            //Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getStackTrace());
        } catch (ExecutionException ex) {
            //Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getStackTrace());
        }

    }
}