简体   繁体   中英

Increase or Decrease Swing Timer Speed with Buttons?

This question is expanding on another I had gotten help with via Stackoverflow ( Update JLabel every X seconds from ArrayList<List> - Java ) on making my label update every X seconds. Anyhow... I would now like to Increase or Decrease the speed of the timer and have it loop through the file over an over again.

My print statement looks like so: (int tM is set at 300 currently...)

private void printWords() {
        final Timer timer = new Timer(tM, null);

        ActionListener listener = new ActionListener() {
            private Iterator<Word> w = words.iterator();
            @Override 
            public void actionPerformed(ActionEvent e) {
                if (w.hasNext()) {
                    _textField.setText(w.next().getName());
                    //Prints to Console just Fine...
                    //System.out.println(w.next().getName());   
                }
                else {
                    timer.stop();
                }
            }
        };
        timer.addActionListener(listener);
        bPlay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              timer.start();
            }
          });
        bPause.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              timer.stop();
            }
          });

}

What I would like to do is increase or decrease the speed with a couple of other buttons, Faster and Slower.

How do I go about changing the timer interval mid use?

bFaster.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              tM = 100;
            }
          });
        bSlower.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              tM = 1000;
            }
          });

Thanks for any ideas.

Yours, JF

Can't you do the following? The timing won't be perfect but probably not noticeable to the user:

   bFaster.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          tM = 100;
          timer.stop();
          timer.setDelay( tM );
          timer.start();
        }
      });
    bSlower.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          tM = 1000;
          timer.stop();
          timer.setDelay( tM );
          timer.start();
        }
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM