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:fr.duminy.jbackup.core.JBackupImpl.java

@Override
public Timer shutdown(final TerminationListener listener) throws InterruptedException {
    executor.shutdown();/*from   w ww .  j a v  a  2 s  . c o  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:ProgressBarDemo.java

public ProgressBarDemo() {
    super(new BorderLayout());
    task = new LongTask();

    //Create the demo's UI.
    startButton = new JButton("Start");
    startButton.setActionCommand("start");
    startButton.addActionListener(this);

    progressBar = new JProgressBar(0, task.getLengthOfTask());
    progressBar.setValue(0);/* w  w w .ja  v  a  2s .  c om*/
    progressBar.setStringPainted(true);

    taskOutput = new JTextArea(5, 20);
    taskOutput.setMargin(new Insets(5, 5, 5, 5));
    taskOutput.setEditable(false);
    taskOutput.setCursor(null); //inherit the panel's cursor
                                //see bug 4851758

    JPanel panel = new JPanel();
    panel.add(startButton);
    panel.add(progressBar);

    add(panel, BorderLayout.PAGE_START);
    add(new JScrollPane(taskOutput), BorderLayout.CENTER);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    //Create a timer.
    timer = new Timer(ONE_SECOND, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            progressBar.setValue(task.getCurrent());
            String s = task.getMessage();
            if (s != null) {
                taskOutput.append(s + newline);
                taskOutput.setCaretPosition(taskOutput.getDocument().getLength());
            }
            if (task.isDone()) {
                Toolkit.getDefaultToolkit().beep();
                timer.stop();
                startButton.setEnabled(true);
                setCursor(null); //turn off the wait cursor
                progressBar.setValue(progressBar.getMinimum());
            }
        }
    });
}

From source file:org.jfree.chart.demo.ChartTiming3.java

/**
 * Runs the test./*from   ww w .  java2  s .c om*/
 */
public void run() {

    this.finished = false;

    // create a dataset...
    final XYSeries series = new XYSeries("Random Data");
    for (int i = 0; i < 1440; i++) {
        final double x = Math.random();
        final double y = Math.random();
        series.add(x, y);
    }
    final XYDataset data = new XYSeriesCollection(series);

    // create a scatter chart...
    final boolean withLegend = true;
    final JFreeChart chart = ChartFactory.createScatterPlot("Scatter plot timing", "X", "Y", data,
            PlotOrientation.VERTICAL, withLegend, false, false);

    final XYPlot plot = chart.getXYPlot();
    plot.setRenderer(new XYDotRenderer());

    final BufferedImage image = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
    final Graphics2D g2 = image.createGraphics();
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 400, 300);

    // set up the timer...
    final Timer timer = new Timer(10000, this);
    timer.setRepeats(false);
    int count = 0;
    timer.start();
    while (!this.finished) {
        chart.draw(g2, chartArea, null, null);
        System.out.println("Charts drawn..." + count);
        if (!this.finished) {
            count++;
        }
    }
    System.out.println("DONE");

}

From source file:patientview.HistoryJFrame.java

/**
 * Creates new form HistoryJFrame/*from w w  w  .  ja v  a2  s  .  c  o m*/
 */
public HistoryJFrame(int bedNum, int time, Patients patients) {
    initComponents();

    //set window in the center of the screen
    //Get the size of the screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    //Determine the new location of the window
    int w = this.getSize().width;
    int h = this.getSize().height;
    int x = (dim.width - w) / 2;
    int y = (dim.height - h) / 2;
    //Move the window
    this.setLocation(x, y);

    //Load click sound
    try {
        AudioInputStream audioInputStream = AudioSystem
                .getAudioInputStream(new File("sounds/click.wav").getAbsoluteFile());
        click = AudioSystem.getClip();
        click.open(audioInputStream);
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

    //Get patient
    this.patients = patients;
    this.bedNum = bedNum;
    thisPatient = patients.getPatient(bedNum);

    //Set background colour
    this.getContentPane().setBackground(new Color(240, 240, 240));

    //fill titles
    wardNumField.setText("W001");
    bedNumField.setText(String.valueOf(bedNum));

    checkBoxes = new ArrayList<JCheckBox>() {
        {
            add(jCheckBox1);
            add(jCheckBox2);
            add(jCheckBox3);
            add(jCheckBox4);
            add(jCheckBox5);
            add(jCheckBox6);
        }
    };

    genGraph(getGraphCode());

    //set timer
    timerCSeconds = time;
    if (timer == null) {
        timer = new Timer(10, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // do it every 10 msecond
                Calendar cal = Calendar.getInstance();
                cal.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                jLabel_systemTime.setText(sdf.format(cal.getTime()));
                // do it every 5 seconds
                if (timerCSeconds % 500 == 0) {
                    //genGraph(getGraphCode()); //only useful for dispalying data up until the current moment
                }

                timerCSeconds++;
            }
        });
    }

    if (timer.isRunning() == false) {
        timer.start();
    }
}

From source file:de.weltraumschaf.minesweeper.model.MinesweeperSession.java

/**
 * Initialize the status bar./*from  ww w. j  ava 2  s  .  c om*/
 */
private void initStatusBar() {
    LOG.debug("Init status bar.");
    score.addObserver(mainWindow.getStatusbar());
    timer = new Timer(TIMER_DELAY, new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            mainWindow.getStatusbar().setElapsedTime(currentGame.getTime());
        }
    });
    timer.setRepeats(true);
    timer.setCoalesce(true);
    timer.setInitialDelay(0);
    timer.start();
}

From source file:cz.alej.michalik.totp.client.OtpPanel.java

/**
 * Pid jeden panel se zznamem/*from   w ww.j av  a  2 s . com*/
 * 
 * @param raw_data
 *            Data z Properties
 * @param p
 *            Properties
 * @param index
 *            Index zznamu - pro vymazn
 */
public OtpPanel(String raw_data, final Properties p, final int index) {
    // Data jsou oddlena stednkem
    final String[] data = raw_data.split(";");

    // this.setBackground(App.COLOR);
    this.setLayout(new GridBagLayout());
    // Mkov rozloen prvk
    GridBagConstraints c = new GridBagConstraints();
    this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100));

    // Tla?tko pro zkoprovn hesla
    final JButton passPanel = new JButton("");
    passPanel.setFont(passPanel.getFont().deriveFont(App.FONT_SIZE));
    passPanel.setBackground(App.COLOR);
    // Zabere celou ku
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 100;
    this.add(passPanel, c);
    passPanel.setText(data[0]);

    // Tla?tko pro smazn
    JButton delete = new JButton("X");
    try {
        String path = "/material-design-icons/action/drawable-xhdpi/ic_delete_black_24dp.png";
        Image img = ImageIO.read(App.class.getResource(path));
        delete.setIcon(new ImageIcon(img));
        delete.setText("");
    } catch (Exception e) {
        System.out.println("Icon not found");
    }
    delete.setFont(delete.getFont().deriveFont(App.FONT_SIZE));
    delete.setBackground(App.COLOR);
    // Zabere kousek vpravo
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.5;
    c.anchor = GridBagConstraints.EAST;
    this.add(delete, c);

    // Akce pro vytvoen a zkoprovn hesla do schrnky
    passPanel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Generuji kod pro " + data[1]);
            System.out.println(new Base32().decode(data[1].getBytes()).length);
            clip.set(new TOTP(new Base32().decode(data[1].getBytes())).toString());
            System.out.printf("Kd pro %s je ve schrnce\n", data[0]);
            passPanel.setText("Zkoprovno");
            // Zobraz zprvu na 1 vteinu
            int time = 1000;
            // Animace zobrazen zprvy po zkoprovn
            final Timer t = new Timer(time, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    passPanel.setText(data[0]);
                }
            });
            t.start();
            t.setRepeats(false);
        }
    });

    // Akce pro smazn panelu a uloen zmn
    delete.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.printf("Odstrann %s s indexem %d\n", data[0], index);
            p.remove(String.valueOf(index));
            App.saveProperties();
            App.loadProperties();
        }
    });

}

From source file:BouncingBall.java

public BouncingBall() {
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
    Canvas3D c = new Canvas3D(config);
    add("Center", c);
    c.addKeyListener(this);
    timer = new Timer(100, this);
    //timer.start();
    Panel p = new Panel();
    p.add(go);// w  ww .jav a 2s.c o m
    add("North", p);
    go.addActionListener(this);
    go.addKeyListener(this);
    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    SimpleUniverse u = new SimpleUniverse(c);
    u.getViewingPlatform().setNominalViewingTransform();
    u.addBranchGraph(scene);
}

From source file:InternalFrameListenerDemo.java

public InternalFrameListenerDemo() {
    setTitle("Animated InternalFrameListener");
    m_count = m_tencount = 0;//from  www.  j  a  v a2 s. co  m

    JPanel innerListenerPanel = new JPanel(new GridLayout(7, 1));
    JPanel listenerPanel = new JPanel(new BorderLayout());
    m_ifEventCanvas = new IFEventCanvas();

    m_lOpened = new JLabel("internalFrameOpened");
    m_lClosing = new JLabel("internalFrameClosing");
    m_lClosed = new JLabel("internalFrameClosed");
    m_lIconified = new JLabel("internalFrameIconified");
    m_lDeiconified = new JLabel("internalFrameDeiconified");
    m_lActivated = new JLabel("internalFrameActivated");
    m_lDeactivated = new JLabel("internalFrameDeactivated");

    innerListenerPanel.add(m_lOpened);
    innerListenerPanel.add(m_lClosing);
    innerListenerPanel.add(m_lClosed);
    innerListenerPanel.add(m_lIconified);
    innerListenerPanel.add(m_lDeiconified);
    innerListenerPanel.add(m_lActivated);
    innerListenerPanel.add(m_lDeactivated);

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

    m_desktop = new JDesktopPane();
    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, 500);
    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();
}

From source file:components.SliderDemo.java

public SliderDemo() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    delay = 1000 / FPS_INIT;//w w  w . j a v  a 2 s  .c  om

    //Create the label.
    JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
    sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

    //Create the slider.
    JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, FPS_MIN, FPS_MAX, FPS_INIT);

    framesPerSecond.addChangeListener(this);

    //Turn on labels at major tick marks.

    framesPerSecond.setMajorTickSpacing(10);
    framesPerSecond.setMinorTickSpacing(1);
    framesPerSecond.setPaintTicks(true);
    framesPerSecond.setPaintLabels(true);
    framesPerSecond.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
    Font font = new Font("Serif", Font.ITALIC, 15);
    framesPerSecond.setFont(font);

    //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(sliderLabel);
    add(framesPerSecond);
    add(picture);
    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:gdt.jgui.console.JItemPanel.java

protected void createTimer() {
    timer = new Timer(100, new ActionListener() {
        @Override/*from w w  w  .j  a va 2s .c  om*/
        public void actionPerformed(ActionEvent e) {
            //System.out.println("ItemPanel:createTimer:timer done ");
            title.setBackground(JItemPanel.this.getBackground());
            String locator$ = JItemPanel.this.locator$;
            JConsoleHandler.execute(JItemPanel.this.console, locator$);
            timer.stop();
        }
    });
}