Example usage for javax.swing Timer Timer

List of usage examples for javax.swing Timer Timer

Introduction

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

Prototype

public Timer(int delay, ActionListener listener) 

Source Link

Document

Creates a Timer and initializes both the initial delay and between-event delay to delay milliseconds.

Usage

From source file:DigitalClock.java

public DigitalClock() {
    // Set default values for our properties
    setFormat(DateFormat.getTimeInstance(DateFormat.MEDIUM, getLocale()));
    setUpdateFrequency(1000); // Update once a second

    // Specify a Swing TransferHandler object to do the dirty work of
    // copy-and-paste and drag-and-drop for us. This one will transfer
    // the value of the "time" property. Since this property is read-only
    // it will allow drags but not drops.
    setTransferHandler(new TransferHandler("time"));

    // Since JLabel does not normally support drag-and-drop, we need an
    // event handler to detect a drag and start the transfer.
    addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {
            getTransferHandler().exportAsDrag(DigitalClock.this, e, TransferHandler.COPY);
        }//from  ww  w. ja v a2s  . c o  m
    });

    // Before we can have a keyboard binding for a Copy command,
    // the component needs to be able to accept keyboard focus.
    setFocusable(true);
    // Request focus when we're clicked on
    addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            requestFocus();
        }
    });
    // Use a LineBorder to indicate when we've got the keyboard focus
    addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            setBorder(LineBorder.createBlackLineBorder());
        }

        public void focusLost(FocusEvent e) {
            setBorder(null);
        }
    });

    // Now bind the Ctrl-C keystroke to a "Copy" command.
    InputMap im = new InputMap();
    im.setParent(getInputMap(WHEN_FOCUSED));
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK), "Copy");
    setInputMap(WHEN_FOCUSED, im);

    // And bind the "Copy" command to a pre-defined Action that performs
    // a copy using the TransferHandler we've installed.
    ActionMap am = new ActionMap();
    am.setParent(getActionMap());
    am.put("Copy", TransferHandler.getCopyAction());
    setActionMap(am);

    // Create a javax.swing.Timer object that will generate ActionEvents
    // to tell us when to update the displayed time. Every updateFrequency
    // milliseconds, this timer will cause the actionPerformed() method
    // to be invoked. (For non-GUI applications, see java.util.Timer.)
    timer = new Timer(updateFrequency, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setText(getTime()); // set label to current time string
        }
    });
    timer.setInitialDelay(0); // Do the first update immediately
    timer.start(); // Start timing now!
}

From source file:com.polivoto.vistas.AnalistaLocal.java

/**
 * Creates new form AnalistaD/*from www.j  ava2 s. com*/
 *
 * @param accionesConsultor
 */
public AnalistaLocal(AccionesConsultor accionesConsultor) {
    this.accionesConsultor = accionesConsultor;
    initComponents();
    cardsPreguntas = new CardLayout();
    panelPreguntas.setLayout(cardsPreguntas);
    setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
    panelVotando.setVisible(true);
    Panel3.setVisible(false);
    try {
        String startupDataString = this.accionesConsultor.consultaParametrosIniciales();
        json = new JSONObject(startupDataString);
        this.accionesConsultor.consultaPreguntas();
        long tFinal = json.getLong("tiempo_final");
        cronometro = new Cronometro(lblhrs, lblmin, lblseg, tFinal);
        cronometro.iniciarCronometro();
        System.out.println("Startup data: " + startupDataString);
        escuchar = new RecibirVotos();
        poblacion = json.getInt("poblacion");
        votos = json.getInt("votos");
        System.out.println("" + json.toString());
    } catch (IOException | JSONException ignore) {
        ignore.printStackTrace();
    }
    // Obtener el nombre de la zona
    panelMain.setLayout(cardLayout);
    panelMain.add(Panel1, "1");
    panelMain.add(Panel2, "2");
    panelMain.add(Panel3, "3");
    cardLayout.show(panelMain, "1");
    System.out.println("Startup dada: " + json.toString());
    escuchar.iniciarEscucha(votos, poblacion, lblvotos_totales, lblporcentaje, pnlgrafica);
    Service service = new Service();
    service.start();
    setPreguntasText();
    timerPaneles = new Timer(6000, new PanelesPreguntas());
    timerPaneles.start();
}

From source file:components.SliderDemo2.java

public SliderDemo2() {
    super(new BorderLayout());

    delay = 1000 / FPS_INIT;/*from   www. j a v  a 2 s . c  o  m*/

    //Create the slider.
    JSlider framesPerSecond = new JSlider(JSlider.VERTICAL, FPS_MIN, FPS_MAX, FPS_INIT);
    framesPerSecond.addChangeListener(this);
    framesPerSecond.setMajorTickSpacing(10);
    framesPerSecond.setPaintTicks(true);

    //Create the label table.
    Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
    //PENDING: could use images, but we don't have any good ones.
    labelTable.put(new Integer(0), new JLabel("Stop"));
    //new JLabel(createImageIcon("images/stop.gif")) );
    labelTable.put(new Integer(FPS_MAX / 10), new JLabel("Slow"));
    //new JLabel(createImageIcon("images/slow.gif")) );
    labelTable.put(new Integer(FPS_MAX), new JLabel("Fast"));
    //new JLabel(createImageIcon("images/fast.gif")) );
    framesPerSecond.setLabelTable(labelTable);

    framesPerSecond.setPaintLabels(true);
    framesPerSecond.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));

    //Create the label that displays the animation.
    picture = new JLabel();
    picture.setHorizontalAlignment(JLabel.CENTER);
    picture.setAlignmentX(Component.CENTER_ALIGNMENT);
    picture.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLoweredBevelBorder(),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    updatePicture(0); //display first frame

    //Put everything together.
    add(framesPerSecond, BorderLayout.LINE_START);
    add(picture, BorderLayout.CENTER);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    //Set up a timer that calls this object's action handler.
    timer = new Timer(delay, this);
    timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
                                      //by restarting the timer
    timer.setCoalesce(true);
}

From source file:Views.GraphView.java

public GraphView(RegularTimePeriod T, String title, double openPrice) {
    graphTitle = title;/*  w w  w.  j a va  2 s.  co m*/

    lastValueAsk = openPrice;
    lastValueBid = openPrice;
    lastValueExecuted = openPrice;

    newValueAsk = openPrice;
    newValueBid = openPrice;
    lastexectuednew = openPrice;

    this.BidValuePlot = new TimeSeries("Bid", Millisecond.class);
    this.AskValuePlot = new TimeSeries("Ask", Millisecond.class);
    this.VolumeBidPlot = new TimeSeries("Volume Bid", Millisecond.class);
    this.VolumeAskPlot = new TimeSeries("Volume Ask", Millisecond.class);
    this.ExecutedValuePlot = new TimeSeries("Last Executed", Millisecond.class);
    this.VolumeExecPlot = new TimeSeries("Volume Last Executed", Millisecond.class);

    this.Tdebut = T;
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(BidValuePlot);
    dataset.addSeries(AskValuePlot);
    this.BidValuePlot.add(Tdebut, lastValueBid);
    this.AskValuePlot.add(Tdebut, lastValueAsk);
    dataset2 = new TimeSeriesCollection();
    dataset2.addSeries(VolumeBidPlot);
    dataset2.addSeries(VolumeAskPlot);
    this.VolumeBidPlot.add(Tdebut, lastVolumeBid);
    this.VolumeAskPlot.add(Tdebut, lastVolumeAsk);

    dataset3 = new TimeSeriesCollection();
    dataset3.addSeries(ExecutedValuePlot);
    dataset4 = new TimeSeriesCollection();

    dataset4.addSeries(VolumeExecPlot);
    chart = createChart(dataset);

    //Sets background color of chart
    chart.setBackgroundPaint(Color.LIGHT_GRAY);
    chartPanel = new ChartPanel(chart);

    timer = new Timer(0, this);
    timer.start();

}

From source file:me.mayo.telnetkek.ConnectionManager.java

public void sendDelayedCommand(final String text, final boolean verbose, final int delay) {
    final Timer timer = new Timer(delay, event -> sendCommand(text, verbose));
    timer.setRepeats(false);//from www.j  ava 2  s. co  m
    timer.start();
}

From source file:SwingGlassExample.java

public void startTimer() {
    if (timer == null) {
        timer = new Timer(1000, new ActionListener() {
            int progress = 0;

            public void actionPerformed(ActionEvent A) {
                progress += 10;/* w  w  w.  j  ava2s . c  o  m*/
                waiter.setValue(progress);

                // Once we hit 100%, remove the glass pane and reset the
                // progress bar stuff
                if (progress >= 100) {
                    progress = 0;
                    timer.stop();
                    glass.setVisible(false);
                    // Again, manually control our 1.2/1.3 bug workaround
                    glass.setNeedToRedispatch(true);
                    waiter.setValue(0);
                }
            }
        });
    }
    if (timer.isRunning()) {
        timer.stop();
    }
    timer.start();
}

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 . co m
                }
            }
        });
        tm.setRepeats(false);
        tm.start();
    }
}

From source file:uk.co.petertribble.jkstat.gui.KstatBaseChart.java

/**
 * Start the loop that updates the chart regularly.
 *//*  w  w  w .  j a va  2 s .  co  m*/
public void startLoop() {
    if (timer == null) {
        timer = new Timer(delay, this);
    }
    timer.start();
}

From source file:Interfaz.rubiktimer.java

public rubiktimer() {

    addKeyListener(this); //acciones para el teclado
    initComponents(); //compentes(codigo generado)
    this.setSize(1305, 765); //size de la interfaz 
    setLocationRelativeTo(null);//posicion
    t = new Timer(10, acciones); //tiempo prinicipal
    t_atras = new Timer(900, acciones_crono_atras); //tiempo conteo atras

}

From source file:DesktopManagerDemo.java

public DesktopManagerDemo() {
    setTitle("Animated DesktopManager");
    m_count = m_tencount = 0;//from ww w . jav a2s .c om

    JPanel innerListenerPanel = new JPanel(new GridLayout(15, 1));
    JPanel listenerPanel = new JPanel(new BorderLayout());
    m_dmEventCanvas = new DMEventCanvas();

    m_lActivates = new JLabel("activateFrame");
    m_lBegindrags = new JLabel("beginDraggingFrame");
    m_lBeginresizes = new JLabel("beginResizingFrame");
    m_lCloses = new JLabel("closeFrame");
    m_lDeactivates = new JLabel("deactivateFrame");
    m_lDeiconifies = new JLabel("deiconifyFrame");
    m_lDrags = new JLabel("dragFrame");
    m_lEnddrags = new JLabel("endDraggingFrame");
    m_lEndresizes = new JLabel("endResizingFrame");
    m_lIconifies = new JLabel("iconifyFrame");
    m_lMaximizes = new JLabel("maximizeFrame");
    m_lMinimizes = new JLabel("minimizeFrame");
    m_lOpens = new JLabel("openFrame");
    m_lResizes = new JLabel("resizeFrame");
    m_lSetbounds = new JLabel("setBoundsForFrame");

    innerListenerPanel.add(m_lActivates);
    innerListenerPanel.add(m_lBegindrags);
    innerListenerPanel.add(m_lBeginresizes);
    innerListenerPanel.add(m_lCloses);
    innerListenerPanel.add(m_lDeactivates);
    innerListenerPanel.add(m_lDeiconifies);
    innerListenerPanel.add(m_lDrags);
    innerListenerPanel.add(m_lEnddrags);
    innerListenerPanel.add(m_lEndresizes);
    innerListenerPanel.add(m_lIconifies);
    innerListenerPanel.add(m_lMaximizes);
    innerListenerPanel.add(m_lMinimizes);
    innerListenerPanel.add(m_lOpens);
    innerListenerPanel.add(m_lResizes);
    innerListenerPanel.add(m_lSetbounds);

    listenerPanel.add("Center", m_dmEventCanvas);
    listenerPanel.add("West", innerListenerPanel);
    listenerPanel.setOpaque(true);
    listenerPanel.setBackground(Color.white);

    m_myDesktopManager = new MyDesktopManager();
    m_desktop = new JDesktopPane();
    m_desktop.setDesktopManager(m_myDesktopManager);
    m_desktop.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
    m_newFrame = new JButton("New Frame");
    m_newFrame.addActionListener(this);
    m_infos = UIManager.getInstalledLookAndFeels();
    String[] LAFNames = new String[m_infos.length];
    for (int i = 0; i < m_infos.length; i++) {
        LAFNames[i] = m_infos[i].getName();
    }
    m_UIBox = new JComboBox(LAFNames);
    m_UIBox.addActionListener(this);
    JPanel topPanel = new JPanel(true);
    topPanel.setLayout(new FlowLayout());
    topPanel.setBorder(new CompoundBorder(new SoftBevelBorder(BevelBorder.LOWERED),
            new CompoundBorder(new EmptyBorder(2, 2, 2, 2), new SoftBevelBorder(BevelBorder.RAISED))));
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add("North", topPanel);
    getContentPane().add("Center", m_desktop);
    getContentPane().add("South", listenerPanel);
    ((JPanel) getContentPane()).setBorder(new CompoundBorder(new SoftBevelBorder(BevelBorder.LOWERED),
            new CompoundBorder(new EmptyBorder(1, 1, 1, 1), new SoftBevelBorder(BevelBorder.RAISED))));
    topPanel.add(m_newFrame);
    topPanel.add(new JLabel("Look & Feel:", SwingConstants.RIGHT));
    topPanel.add(m_UIBox);
    setSize(645, 600);
    Dimension dim = getToolkit().getScreenSize();
    setLocation(dim.width / 2 - getWidth() / 2, dim.height / 2 - getHeight() / 2);
    setVisible(true);
    WindowListener l = new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    addWindowListener(l);
    m_eventTimer = new Timer(1000, this);
    m_eventTimer.setRepeats(true);
    m_eventTimer.start();
}