简体   繁体   中英

How do I make my for loop delay for 1 second between iterations on JFrame?

This is my function so far:

    public void slow_print(final String s, int interval){
        for (int i=0; i<s.length(); i++){
            txta_main.setText(
                txta_main.getText()
                + String.valueOf(s.charAt(i))
            );
        }
    }

I don't know how to make it wait in between setText calls. I can't use Thread.sleep as this is on a GUI and the sleep freezes the output until the whole string is done.

Use a Swing Timer for basic animation.

The Timer replaces your looping logic.

Every time the timer fires your increment your "index" variable and perform your processing.

Here is a simple that example that simply increments the index variable and stops when processing has completed 10 cycles.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class TimerStop extends JPanel implements ActionListener
{
    private JLabel timeLabel;
    private int count = 0;

    public TimerStop()
    {
        timeLabel = new JLabel( new Date().toString() );
        add( timeLabel );

        Timer timer = new Timer(1000, this);
        timer.setInitialDelay(1);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        timeLabel.setText( new Date().toString() );
        count++;
        System.out.println(count);

        if (count == 10)
        {
            Timer timer = (Timer)e.getSource();
            timer.stop();
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("TimerStop");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TimerStop() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

So you simply modify the timer logic to append a character to the text string each time the Timer fires and stop the timer then all the text is displayed.

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