Example usage for javax.swing Timer start

List of usage examples for javax.swing Timer start

Introduction

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

Prototype

public void start() 

Source Link

Document

Starts the Timer, causing it to start sending action events to its listeners.

Usage

From source file:net.sf.jabref.gui.MainTableSelectionListener.java

private void updatePreview(final BibtexEntry toShow, final boolean changedPreview, int repeats) {
    if (workingOnPreview) {
        if (repeats > 0) {
            return; // We've already waited once. Give up on this selection.
        }/*from  ww  w  .j  a  v  a 2  s.co m*/
        Timer t = new Timer(50, actionEvent -> updatePreview(toShow, changedPreview, 1));
        t.setRepeats(false);
        t.start();
        return;
    }
    EventList<BibtexEntry> list = table.getSelected();
    // Check if the entry to preview is still selected:
    if ((list.size() != 1) || (list.get(0) != toShow)) {
        return;
    }
    final int mode = panel.getMode();
    workingOnPreview = true;
    SwingUtilities.invokeLater(() -> {
        preview.setEntry(toShow);

        // If nothing was already shown, set the preview and move the separator:
        if (changedPreview || (mode == BasePanel.SHOWING_NOTHING)) {
            panel.showPreview(preview);
            panel.adjustSplitter();
        }
        workingOnPreview = false;
    });
}

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

@Override
public Timer shutdown(final TerminationListener listener) throws InterruptedException {
    executor.shutdown();/*from w  w  w  . j  a v  a2  s. 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.leo.benchmark.Benchmark.java

/**
 * Execute the current run code loop times.
 * /*from   www. java2  s .  co  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:me.mayo.telnetkek.MainPanel.java

private void writeToConsoleImmediately(final ConsoleMessage message, final boolean isTelnetError) {
    SwingUtilities.invokeLater(() -> {
        if (isTelnetError && chkIgnoreErrors.isSelected()) {
            return;
        }//from  ww  w  . j  av a2s  .  c  o  m

        final StyledDocument styledDocument = mainOutput.getStyledDocument();

        int startLength = styledDocument.getLength();

        try {
            styledDocument.insertString(styledDocument.getLength(),
                    message.getMessage() + System.lineSeparator(),
                    StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, message.getColor()));
        } catch (BadLocationException ex) {
            throw new RuntimeException(ex);
        }

        if (MainPanel.this.chkAutoScroll.isSelected() && MainPanel.this.mainOutput.getSelectedText() == null) {
            final JScrollBar vScroll = mainOutputScoll.getVerticalScrollBar();

            if (!vScroll.getValueIsAdjusting()) {
                if (vScroll.getValue() + vScroll.getModel().getExtent() >= (vScroll.getMaximum() - 50)) {
                    MainPanel.this.mainOutput.setCaretPosition(startLength);

                    final Timer timer = new Timer(10, (ActionEvent ae) -> {
                        vScroll.setValue(vScroll.getMaximum());
                    });
                    timer.setRepeats(false);
                    timer.start();
                }
            }
        }
    });
}

From source file:components.MenuSelectionManagerDemo.java

public JMenuBar createMenuBar() {
    JMenuBar menuBar;/*from   w ww.j a  va 2 s  .  c o m*/
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;

    //Create the menu bar.
    menuBar = new JMenuBar();

    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);

    ImageIcon icon = createImageIcon("images/middle.gif");
    menuItem = new JMenuItem("Both text and icon", icon);
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    menuItem = new JMenuItem(icon);
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();

    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);

    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);

    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);

    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription("This menu does nothing");
    menuBar.add(menu);

    Timer timer = new Timer(ONE_SECOND, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
            for (int i = 0; i < path.length; i++) {
                if (path[i].getComponent() instanceof javax.swing.JMenuItem) {
                    JMenuItem mi = (JMenuItem) path[i].getComponent();
                    if ("".equals(mi.getText())) {
                        output.append("ICON-ONLY MENU ITEM > ");
                    } else {
                        output.append(mi.getText() + " > ");
                    }
                }
            }
            if (path.length > 0)
                output.append(newline);
        }
    });
    timer.start();
    return menuBar;
}

From source file:MenuSelectionManagerDemo.java

public JMenuBar createMenuBar() {
    JMenuBar menuBar;/*from  w w w. ja  v a2  s  . c om*/
    JMenu menu, submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;

    //Create the menu bar.
    menuBar = new JMenuBar();

    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
    menuItem.addActionListener(this);
    menu.add(menuItem);

    ImageIcon icon = createImageIcon("1.gif");
    menuItem = new JMenuItem("Both text and icon", icon);
    menuItem.setMnemonic(KeyEvent.VK_B);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    menuItem = new JMenuItem(icon);
    menuItem.setMnemonic(KeyEvent.VK_D);
    menuItem.addActionListener(this);
    menu.add(menuItem);

    //a group of radio button menu items
    menu.addSeparator();
    ButtonGroup group = new ButtonGroup();

    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    rbMenuItem.addActionListener(this);
    menu.add(rbMenuItem);

    //a group of check box menu items
    menu.addSeparator();
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    cbMenuItem.addItemListener(this);
    menu.add(cbMenuItem);

    //a submenu
    menu.addSeparator();
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);

    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
    menuItem.addActionListener(this);
    submenu.add(menuItem);

    menuItem = new JMenuItem("Another item");
    menuItem.addActionListener(this);
    submenu.add(menuItem);
    menu.add(submenu);

    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription("This menu does nothing");
    menuBar.add(menu);

    Timer timer = new Timer(ONE_SECOND, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
            for (int i = 0; i < path.length; i++) {
                if (path[i].getComponent() instanceof javax.swing.JMenuItem) {
                    JMenuItem mi = (JMenuItem) path[i].getComponent();
                    if ("".equals(mi.getText())) {
                        output.append("ICON-ONLY MENU ITEM > ");
                    } else {
                        output.append(mi.getText() + " > ");
                    }
                }
            }
            if (path.length > 0)
                output.append(newline);
        }
    });
    timer.start();
    return menuBar;
}

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  .ja  v a  2s.c  o m*/
    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:FileTreeDragSource.java

public void dragDropEnd(DragSourceDropEvent dsde) {
    DnDUtils.debugPrintln("Drag Source: drop completed, drop action = "
            + DnDUtils.showActions(dsde.getDropAction()) + ", success: " + dsde.getDropSuccess());
    // If the drop action was ACTION_MOVE,
    // the tree might need to be updated.
    if (dsde.getDropAction() == DnDConstants.ACTION_MOVE) {
        final File[] draggedFiles = dragFiles;
        final TreePath[] draggedPaths = paths;

        Timer tm = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Check whether each of the dragged files exists.
                // If it does not, we need to remove the node
                // that represents it from the tree.
                for (int i = 0; i < draggedFiles.length; i++) {
                    if (draggedFiles[i].exists() == false) {
                        // Remove this node
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) draggedPaths[i]
                                .getLastPathComponent();
                        ((DefaultTreeModel) tree.getModel()).removeNodeFromParent(node);
                    }//w w w  .  j  a v a 2 s  . c  om
                }
            }
        });
        tm.setRepeats(false);
        tm.start();
    }
}

From source file:com.qframework.core.GameonApp.java

private void onTextInput(final String resptype, final String respdata) {

    Timer t = new javax.swing.Timer(50, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JTextField area = new JTextField(resptype);
            area.setFocusable(true);/*from  w w w .  jav a  2 s  . c om*/
            area.requestFocus();
            Object options[] = new Object[] { area };
            Frame parent = null;
            if (mAppContext != null)
                parent = (Frame) SwingUtilities.getAncestorOfClass(java.awt.Frame.class, mAppContext);
            else
                parent = (Frame) SwingUtilities.getAncestorOfClass(java.awt.Frame.class, mAppletContext);

            int option = JOptionPane.showOptionDialog(parent, options, "", JOptionPane.YES_OPTION,
                    JOptionPane.INFORMATION_MESSAGE, null, null, null);
            if (option == JOptionPane.YES_OPTION) {
                String truncated = area.getText().replaceAll("[^A-Za-z0-9:.@ ]", "");
                String script = respdata + "('" + truncated + "' , 1);";
                mScript.execScript(script);
            } else {
                String script = respdata + "(undefined, 1);";
                mScript.execScript(script);

            }
        }
    });
    t.setRepeats(false);
    t.start();

}

From source file:com.t3.client.ui.T3Frame.java

private Timer newChatTimer() {
    // Set up the Chat timer to listen for changes
    Timer tm = new Timer(500, new ActionListener() {
        @Override//from w w w.j a v a2  s .c  o  m
        public void actionPerformed(ActionEvent ae) {
            long currentTime = System.currentTimeMillis();
            LinkedMap<String, Long> chatTimers = chatTyperTimers.getChatTypers();
            List<String> removeThese = new ArrayList<String>(chatTimers.size());

            Set<String> playerTimers = chatTimers.keySet();
            for (String player : playerTimers) {
                if (currentTime - chatTimers.get(player) >= (chatNotifyDuration * 1000)) {
                    // set up a temp place and remove them after the loop
                    removeThese.add(player);
                }
            }
            for (String remove : removeThese) {
                chatTyperTimers.removeChatTyper(remove);
            }
        }
    });
    tm.start();
    return tm;
}