Example usage for javax.swing Timer stop

List of usage examples for javax.swing Timer stop

Introduction

In this page you can find the example usage for javax.swing Timer stop.

Prototype

public void stop() 

Source Link

Document

Stops the Timer, causing it to stop sending action events to its listeners.

Usage

From source file:Main.java

/**
 * Creates an animation to fade the dialog opacity from 0 to 1.
 *
 * @param dialog the dialog to fade in/*from w  w  w. j a v  a 2  s  .  c om*/
 * @param delay the delay in ms before starting and between each change
 * @param incrementSize the increment size
 */
public static void fadeIn(final JDialog dialog, int delay, final float incrementSize) {
    final Timer timer = new Timer(delay, null);
    timer.setRepeats(true);
    timer.addActionListener(new ActionListener() {
        private float opacity = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            opacity += incrementSize;
            dialog.setOpacity(Math.min(opacity, 1)); // requires java 1.7
            if (opacity >= 1) {
                timer.stop();
            }
        }
    });

    dialog.setOpacity(0); // requires java 1.7
    timer.start();
    dialog.setVisible(true);
}

From source file:Main.java

/**
 * Creates an animation to fade the dialog opacity from 1 to 0.
 *//*  w  w  w .  j  a  v a 2  s.c  o  m*/
public static void fadeOut(final JDialog dialog) {
    final Timer timer = new Timer(10, null);
    timer.setRepeats(true);
    timer.addActionListener(new ActionListener() {

        private float opacity = 1;

        @Override
        public void actionPerformed(ActionEvent e) {
            opacity -= 0.15f;
            dialog.setOpacity(Math.max(opacity, 0));
            if (opacity <= 0) {
                timer.stop();
                dialog.dispose();
            }
        }
    });

    dialog.setOpacity(1);
    timer.start();
}

From source file:Main.java

/**
 * Creates an animation to fade the dialog opacity from 0 to 1, wait at 1
 * and then fade to 0 and dispose./*  ww  w.  j a  v  a2  s .  com*/
 *
 * @param dialog the dialog to display
 * @param delay the delay in ms before starting and between each change
 * @param incrementSize the increment size
 * @param displayTime the time in ms the dialog is fully visible
 */
public static void fadeInAndOut(final JDialog dialog, final int delay, final float incrementSize,
        final int displayTime) {
    final Timer timer = new Timer(delay, null);
    timer.setRepeats(true);
    timer.addActionListener(new ActionListener() {
        private float opacity = 0;
        private boolean displayed = false;

        @Override
        public void actionPerformed(ActionEvent e) {

            if (!displayed) {
                opacity += incrementSize;
                dialog.setOpacity(Math.min(opacity, 1)); // requires java 1.7
                if (opacity >= 1) {
                    timer.setDelay(displayTime);
                    displayed = true;
                }
            } else {
                timer.setDelay(delay);
                opacity -= incrementSize;
                dialog.setOpacity(Math.max(opacity, 0)); // requires java 1.7
                if (opacity < 0) {
                    timer.stop();
                    dialog.dispose();
                }
            }
        }
    });

    dialog.setOpacity(0); // requires java 1.7
    timer.start();
    dialog.setVisible(true);
}

From source file:fr.duminy.jbackup.core.JBackupImpl.java

@Override
public Timer shutdown(final TerminationListener listener) throws InterruptedException {
    executor.shutdown();/*from www  . ja va  2s .  co m*/

    Timer timer = null;
    if (listener != null) {
        timer = new Timer(0, null);
        timer.setDelay((int) TimeUnit.SECONDS.toMillis(1));
        final Timer finalTimer = timer;
        timer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (executor.isTerminated()) {
                    listener.terminated();
                    finalTimer.stop();
                }
            }
        });
        timer.setRepeats(true);
        timer.start();
    }

    return timer;
}

From source file:org.micromanager.CRISP.CRISPFrame.java

private void CalibrateButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CalibrateButton_ActionPerformed
    try {//from   w  w w.  j a  va 2 s.  c  om
        core_.setProperty(CRISP_, "CRISP State", "loG_cal");

        String state = "";
        int counter = 0;
        while (!state.equals("loG_cal") && counter < 50) {
            state = core_.getProperty(CRISP_, "CRISP State");
            Thread.sleep(100);
        }
        Double snr = new Double(core_.getProperty(CRISP_, "Signal Noise Ratio"));

        if (snr < 2.0)
            ReportingUtils.showMessage("Signal Noise Ratio is smaller than 2.0.  "
                    + "Focus on your sample, increase LED intensity and try again.");

        core_.setProperty(CRISP_, "CRISP State", "Dither");

        String value = core_.getProperty(CRISP_, "Dither Error");

        final JLabel jl = new JLabel();
        final JLabel jlA = new JLabel();
        final JLabel jlB = new JLabel();
        final String msg1 = "Value:  ";
        final String msg2 = "Adjust the detector lateral adjustment screw until the value is > 100 or"
                + "< -100 and stable.";
        jlA.setText(msg1);
        jl.setText(value);
        jl.setAlignmentX(JLabel.CENTER);

        Object[] msg = { msg1, jl, msg2 };

        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    jl.setText(core_.getProperty(CRISP_, "Dither Error"));
                } catch (Exception ex) {
                    ReportingUtils.logError("Error while getting CRISP dither Error");
                }
            }
        };

        Timer timer = new Timer(100, al);
        timer.setInitialDelay(500);
        timer.start();

        /*JOptionPane optionPane = new JOptionPane(new JLabel("Hello World",JLabel.CENTER));
        JDialog dialog = optionPane.createDialog("");
        dialog.setModal(true);
        dialog.setVisible(true); */

        JOptionPane.showMessageDialog(null, msg, "CRISP Calibration", JOptionPane.OK_OPTION);

        timer.stop();

        core_.setProperty(CRISP_, "CRISP State", "gain_Cal");

        counter = 0;
        while (!state.equals("Ready") && counter < 50) {
            state = core_.getProperty(CRISP_, "CRISP State");
            Thread.sleep(100);
        }
        // ReportingUtils.showMessage("Calibration failed. Focus, make sure that the NA variable is set correctly and try again.");

    } catch (Exception ex) {
        ReportingUtils.showMessage(
                "Calibration failed. Focus, make sure that the NA variable is set correctly and try again.");
    }
}

From source file:org.leo.benchmark.Benchmark.java

/**
 * Execute the current run code loop times.
 * /*  www .ja  v a 2s  .c  o m*/
 * @param run code to run
 * @param loop number of time to run the code
 * @param taskName name displayed at the end of the task
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private void execute(BenchRunnable run, int loop, String taskName) {
    System.out.print(taskName + " ... ");
    // set default context
    collection.clear();
    collection.addAll(defaultCtx);
    // warmup
    warmUp();
    isTimeout = false;
    // timeout timer
    Timer timer = new Timer((int) timeout, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            isTimeout = true;
            // to raise a ConcurrentModificationException or a
            // NoSuchElementException to interrupt internal work in the List
            collection.clear();
        }
    });
    timer.setRepeats(false);
    timer.start();
    long startTime = System.nanoTime();
    int i;
    for (i = 0; i < loop && !isTimeout; i++) {
        try {
            run.run(i);
        } catch (Exception e) {
            // on purpose so ignore it
        }
    }
    timer.stop();
    long time = isTimeout ? timeout * 1000000 : System.nanoTime() - startTime;
    System.out.println((isTimeout ? "Timeout (>" + time + "ns) after " + i + " loop(s)" : time + "ns"));
    // restore default context,
    // the collection instance might have been
    // corrupted by the timeout so create a new instance
    try {
        Constructor<? extends Collection> constructor = collection.getClass()
                .getDeclaredConstructor((Class<?>[]) null);
        constructor.setAccessible(true);
        collection = constructor.newInstance();
        // update the reference
        if (collection instanceof List) {
            list = (List<String>) collection;
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    // store the results for display
    Map<Class<? extends Collection<?>>, Long> currentBench = benchResults.get(taskName);
    if (currentBench == null) {
        currentBench = new HashMap<Class<? extends Collection<?>>, Long>();
        benchResults.put(taskName, currentBench);
    }
    currentBench.put((Class<? extends Collection<String>>) collection.getClass(), time);
    // little gc to clean up all the stuff
    System.gc();
}

From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Runs simulation with plots and logs showing progress, then
    produces report when completed. **/
protected void runSimulation() throws Exception {
    // reset outputs
    this.chartPanel.setChart(null);
    this.reportArea.setText("");
    this.monthlyLogArea.setText("");
    this.tradeLogArea.setText("");

    // create Account
    final double initialCash = ((Number) this.initialCashField.getValue()).doubleValue();
    final double perTradeFee = ((Number) this.perTradeFeeField.getValue()).doubleValue();
    final double perShareTradeCommission = ((Number) this.perShareTradeCommissionField.getValue())
            .doubleValue();/*  w  w  w . j ava2s  .com*/
    final DefaultTradingAccount account = new DefaultTradingAccount(this.histories, perTradeFee,
            perShareTradeCommission);

    // add observers
    account.addTradeObserver(
            new TradeTraceObserver(true, new PrintWriter(new JTextAreaWriter(this.tradeLogArea), true)));
    account.addTradeObserver(new PeriodTraceObserver(1, Calendar.MONTH, true,
            new PrintWriter(new JTextAreaWriter(this.monthlyLogArea), true)));

    final BalanceHistoryObserver balanceObserver = new BalanceHistoryObserver();
    account.addTradeObserver(balanceObserver);

    final TradeWinLossObserver winLossObserver = new TradeWinLossObserver();
    account.addTradeObserver(winLossObserver);

    final PeriodWinLossObserver monthObserver = new PeriodWinLossObserver(1, Calendar.MONTH, true);
    account.addTradeObserver(monthObserver);

    final String betaCompareIndexSymbol = this.compareIndexSymbolField.getText();
    final boolean hasBetaIndex = (histories.get(betaCompareIndexSymbol) != null);
    BetaObserver betaObserver = null;
    if (hasBetaIndex) {
        betaObserver = new BetaObserver(betaCompareIndexSymbol);
        account.addTradeObserver(betaObserver);
    }

    // create strategy
    final String strategyText = this.strategyField.getText().trim();
    final TradingStrategy strategy = loadStrategy(strategyText);
    this.setTitle(strategy.toString());

    // plot with timer update 
    final BalanceHistoryXYDataset accountDataset = new BalanceHistoryXYDataset(balanceObserver);
    final Date startDate = (Date) this.startDateField.getValue();
    final Date endDate = (Date) this.endDateField.getValue();
    final ValueAxis[] yAxes = plotAccountHistory(accountDataset, strategy.toString(), startDate, endDate);

    final ActionListener plotUpdater = new PlotUpdater(accountDataset, yAxes);
    final Timer refreshTimer = new Timer(1000, plotUpdater);// 1000msec cycle
    refreshTimer.start();

    // run simulation
    account.initialize(startDate, initialCash);
    final DefaultTradingSimulator simulator = new DefaultTradingSimulator(histories);
    simulator.runStrategy(strategy, account, startDate, endDate);

    // stop plot timer
    refreshTimer.stop();
    plotUpdater.actionPerformed(null); // one last time.

    // report
    final StringWriter reportWriter = new StringWriter();
    final PrintWriter out = new PrintWriter(reportWriter, true);
    reportSource(out, this.fileField.getText(), startDate, endDate, strategy);
    out.println();
    reportValues(out, initialCash, account);
    if (account.getStockPositionCount() > 0) {
        out.println();
        reportPositions(out, account);
    }
    out.println();
    reportTrades(out, winLossObserver);
    out.println();
    reportMonths(out, monthObserver);
    out.println();
    reportBeta(out, betaObserver, betaCompareIndexSymbol);

    // display report
    this.reportArea.setText(reportWriter.toString());
    this.reportArea.setCaretPosition(0);
    this.vSplit.resetToPreferredSizes();
}

From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java

protected void showNotificationPopup(String popupText, NotificationType type) {
    JPanel panel = new JPanel(new MigLayout("flowy"));
    panel.setBorder(BorderFactory.createLineBorder(Color.gray));

    switch (type) {
    case WARNING:
    case WARNING_HTML:
        panel.setBackground(Color.yellow);
        break;//  w  ww .  j a  v a  2 s  .co m
    case ERROR:
    case ERROR_HTML:
        panel.setBackground(Color.orange);
        break;
    default:
        panel.setBackground(Color.cyan);
    }

    JLabel label = new JLabel(popupText);
    panel.add(label);

    Dimension labelSize = DesktopComponentsHelper.measureHtmlText(popupText);

    int x = frame.getX() + frame.getWidth() - (50 + labelSize.getSize().width);
    int y = frame.getY() + frame.getHeight() - (50 + labelSize.getSize().height);

    PopupFactory factory = PopupFactory.getSharedInstance();
    final Popup popup = factory.getPopup(frame, panel, x, y);
    popup.show();

    panel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            popup.hide();
        }
    });

    PointerInfo pointerInfo = MouseInfo.getPointerInfo();
    if (pointerInfo != null) {
        final Point location = pointerInfo.getLocation();
        final Timer timer = new Timer(3000, null);
        timer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                PointerInfo currentPointer = MouseInfo.getPointerInfo();
                if (currentPointer == null) {
                    timer.stop();
                } else if (!currentPointer.getLocation().equals(location)) {
                    popup.hide();
                    timer.stop();
                }
            }
        });
        timer.start();
    }
}

From source file:net.sourceforge.pmd.cpd.GUI.java

private void go() {
    try {//from www.  ja v a2  s . c  o  m
        File dirPath = new File(rootDirectoryField.getText());
        if (!dirPath.exists()) {
            JOptionPane.showMessageDialog(frame, "Can't read from that root source directory", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        setProgressControls(true);

        Properties p = new Properties();
        CPDConfiguration config = new CPDConfiguration();
        config.setMinimumTileSize(Integer.parseInt(minimumLengthField.getText()));
        config.setEncoding(encodingField.getText());
        config.setIgnoreIdentifiers(ignoreIdentifiersCheckbox.isSelected());
        config.setIgnoreLiterals(ignoreLiteralsCheckbox.isSelected());
        config.setIgnoreAnnotations(ignoreAnnotationsCheckbox.isSelected());
        config.setIgnoreUsings(ignoreUsingsCheckbox.isSelected());
        p.setProperty(LanguageFactory.EXTENSION, extensionField.getText());

        LanguageConfig conf = languageConfigFor((String) languageBox.getSelectedItem());
        Language language = conf.languageFor(p);
        config.setLanguage(language);

        CPDConfiguration.setSystemProperties(config);

        CPD cpd = new CPD(config);
        cpd.setCpdListener(this);
        tokenizingFilesBar.setMinimum(0);
        phaseLabel.setText("");
        if (isLegalPath(dirPath.getPath(), conf)) { // should use the
            // language file filter
            // instead?
            cpd.add(dirPath);
        } else {
            if (recurseCheckbox.isSelected()) {
                cpd.addRecursively(dirPath);
            } else {
                cpd.addAllInDirectory(dirPath);
            }
        }
        Timer t = createTimer();
        t.start();
        cpd.go();
        t.stop();

        matches = new ArrayList<>();
        for (Iterator<Match> i = cpd.getMatches(); i.hasNext();) {
            Match match = i.next();
            setLabelFor(match);
            matches.add(match);
        }

        setListDataFrom(matches);
        String report = new SimpleRenderer().render(cpd.getMatches());
        if (report.length() == 0) {
            JOptionPane.showMessageDialog(frame, "Done. Couldn't find any duplicates longer than "
                    + minimumLengthField.getText() + " tokens");
        } else {
            resultsTextArea.setText(report);
        }
    } catch (IOException t) {
        t.printStackTrace();
        JOptionPane.showMessageDialog(frame, "Halted due to " + t.getClass().getName() + "; " + t.getMessage());
    } catch (RuntimeException t) {
        t.printStackTrace();
        JOptionPane.showMessageDialog(frame, "Halted due to " + t.getClass().getName() + "; " + t.getMessage());
    }
    setProgressControls(false);
}

From source file:nz.govt.natlib.ndha.manualdeposit.bulkupload.BulkUploadQueueManagement.java

private void checkJobQueue() {
    if (closeDownBulkUpload) {
        return;/*from w ww .  j  a v  a  2 s . c  o  m*/
    }
    LOG.debug("Start checkJobQueue");
    int noOfJobsQueryingCMS = 0;
    int noOfJobsNotQueriedCMS = 0;
    int noOfJobsQueryingDPS = 0;
    int noOfJobsNotQueriedDPS = 0;
    int noOfJobsNotQueued = 0;
    int noOfJobsToBeBatched = 0;

    // System.out.println("Start checkJobQueue");
    synchronized (bulkUploadItems) {
        for (BulkUploadItem item : bulkUploadItems) {
            if ((item.getJobState() != JobState.Batching) && (item.getJobState() != JobState.IndigoJobCreated)
                    && (!item.getJobState().isError())) {
                noOfJobsToBeBatched++;
            }
            switch (item.getJobState()) {
            case Requested:
                noOfJobsNotQueriedCMS++;
                break;
            case QueryingCMS:
                noOfJobsQueryingCMS++;
                break;
            case CMSIDRetrieved:
                if (checkDPS) {
                    noOfJobsNotQueriedDPS++;
                } else {
                    noOfJobsNotQueued++;
                }
                break;
            case QueryingDPS:
                noOfJobsQueryingDPS++;
                break;
            case ItemDoesNotExistInDPS:
                if (!checkDPS) {
                    item.setJobState(JobState.CMSIDRetrieved);
                } else {
                    noOfJobsNotQueued++;
                }
                break;
            case ItemExistsInDPS:
                if (!checkDPS) {
                    item.setJobState(JobState.CMSIDRetrieved);
                }
                break;
            case Batching:
                if ((item.getUploadJobState() != null)
                        && (item.getUploadJobState() != UploadJob.JobState.Batching)) {
                    item.setJobState(JobState.IndigoJobCreated);
                }
                break;
            default:
                break;
            }
        }
        if (bulkUploadIsRunning && noOfJobsToBeBatched == 0 && !bulkUploadParent.isLoadingFiles()) {
            bulkUploadIsRunning = false;
        }
        if (noOfJobsNotQueriedCMS > 0
                && noOfJobsQueryingCMS < applicationProperties.getApplicationData().getBulkQueryCount()) {
            int noQuerying = 0;
            for (BulkUploadItem item : bulkUploadItems) {
                if (item.getJobState() == JobState.Requested) {
                    item.retrieveCMSDetails();
                    noQuerying++;
                    if (noQuerying + noOfJobsQueryingCMS >= applicationProperties.getApplicationData()
                            .getBulkQueryCount()) {
                        break;
                    }
                }
            }
        }
        if (checkDPS && noOfJobsNotQueriedDPS > 0
                && noOfJobsQueryingDPS < applicationProperties.getApplicationData().getBulkQueryCount()) {
            for (BulkUploadItem item : bulkUploadItems) {
                if (item.getJobState() == JobState.CMSIDRetrieved) {
                    item.checkDPS();
                }
            }
        }
        if (bulkUploadIsRunning && noOfJobsNotQueued > 0) {
            for (BulkUploadItem item : bulkUploadItems) {
                if (((item.getJobState() == JobState.CMSIDRetrieved) && (!checkDPS))
                        || (item.getJobState() == JobState.ItemDoesNotExistInDPS)) {
                    // System.out.println("Need to batch " + item.getCMSID()
                    // + ": " + item.getJobState().description());
                    if (uploadJob == null) {
                        try {
                            uploadJob = item.createJob();
                        } catch (Exception ex) {
                            LOG.error("Error creating job", ex);
                            // Should be safe to swallow this error as it
                            // would
                            // normally be handled before now.
                        }
                    } else {
                        // System.out.println("Add job " + item.getCMSID());
                        try {
                            item.addToJob(uploadJob);
                        } catch (JobQueueException jex) {
                            LOG.error("Error adding job", jex);
                            // Again, should be safe to swallow this error
                            // as it would
                            // normally be handled before now.
                        }
                    }
                    noOfJobsToBeBatched--;
                    if ((uploadJob.getJobDetail().size() >= userGroup.getBulkBatchSize())
                            || ((noOfJobsToBeBatched == 0) && (!bulkUploadParent.isLoadingFiles()))) {
                        uploadJob.prepareJobToRun();
                        theManualDepositParent.addJob(uploadJob);
                        uploadJob = null;
                    }
                }
            }
        }
    }
    if (theBulkUploadItemsTable != null) {
        theBulkUploadItemsTable.repaint();
    }
    bulkUploadParent.checkButtons();
    Action checkJobQueueAction = new AbstractAction() {
        private static final long serialVersionUID = 5562669711772031634L;

        public void actionPerformed(ActionEvent e) {
            Timer t = (Timer) e.getSource();
            t.stop();
            checkJobQueue();
        }
    };
    new Timer(applicationProperties.getApplicationData().getJobQueueRefreshInterval(), checkJobQueueAction)
            .start();
    LOG.debug("End checkJobQueue");
    // System.out.println("End checkJobQueue");
}