简体   繁体   中英

How to add delay in the for loop using Thread.sleep?

I need to put a delay after each ith iteration inside the for loop. The problem is that probably I cannot use Timer , because I need to use parameters c and k , which depend on previous iteration.

I tried to use Thread.sleep(DELAY) , but it just delays the execution of the whole for loop.

    double c = 3;
    int k = 1;  

    for (int j = 0; j<sumJ; j++)
    {
        for (int i=0; i<sumI; i++)
        {
            //...calculations based on values of c and k 
            // received in previous iterations
            try {
                Thread.sleep(100);
            } catch(InterruptedException ie) {}
        }
    }

OK, here is a very simple example of using a timer. Note that this is a javax.swing.Timer that we are using, which is important, because it makes sure that the work is done in the event thread, which is where all changes to components should be made.

Basically, we create the table and display it, and then, still in the main thread, we prepare the data. Finally, we start the timer, and it triggers an action event every half second, that fills in the next value from the data we prepared.

Note that while the table is filling up, you can play around with the GUI, resize, select cells etc.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.Timer;

class SimpleTest implements ActionListener{

    public static final int ROWS = 10;
    public static final int COLS = 10;
    public static final int DELAY = 500;

    private Integer[][] data = null;
    private int currCol;
    private int currRow;
    private JTable tableToFill = null;
    private Timer theTimer = null;

    /**
     * Calculates the data that should be displayed in the table.
     * In this case it's a simple multiplication table.
     */
    public void fillData() {
        data = new Integer[ROWS][COLS];
        for ( int row = 0; row < ROWS; row++ ) {
            for ( int col = 0; col < COLS; col++) {
                data[row][col] = (row + 1) * (col + 1);
            }
        }
    }

    /**
     * Creates a GUI table to fill up.
     * @return The table object created.
     */
    public JTable setUpJTable() {
        tableToFill = new JTable(ROWS,COLS);
        return tableToFill;
    }

    /**
     * Starts the timer that fills the values in the GUI table
     */
    public void startTimer() {
        if ( tableToFill != null && data != null ) {
            currCol = 0;
            currRow = 0;
            theTimer = new Timer( DELAY, this);
            theTimer.start();
        }
    }

    /**
     * Called by the timer to set the value in the table.
     * 
     * @param evt Action event (not used)
     */
    public void actionPerformed(ActionEvent evt) {
        synchronized (this) {
            if ( currRow < ROWS ) {
                tableToFill.setValueAt(data[currRow][currCol], currRow, currCol);
                currCol++;
                if ( currCol == COLS ) {
                    currCol = 0;
                    currRow++;
                }

            } else {
                theTimer.stop();
            }
        }
    }

    public static void main(String[] args) {

        SimpleTest tableFiller = new SimpleTest();
        JTable table = tableFiller.setUpJTable();

        // Display the table

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(table.getTableHeader(), BorderLayout.PAGE_START);
        frame.getContentPane().add(table, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        // Fill the data, then start displaying it gradually

        tableFiller.fillData();
        tableFiller.startTimer();
    }


}

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