Рисуйте фигуры с задержкой - PullRequest
0 голосов
/ 28 мая 2020

Я знаю, что существуют уже сотни потоков, но я просто не могу этого понять ... У меня есть очень простой класс, который рисует сетку. Я хотел бы добавить задержку в 0,2 секунды после каждого квадрата. Thread.sleep не работает. Какой самый простой способ?

    public Screen() {
        repaint();
    }
    public void paint(Graphics g) {

        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                g.drawRect(50 * i, 50 * j, 50, 50);
                //Add delay
            }
        }
    }

1 Ответ

3 голосов
/ 29 мая 2020

Самый простой способ добиться отложенного рисования - использовать Swing Timer, который является классом, который не блокирует EDT при выполнении. Это позволит вам создать задержку, не блокируя ваш пользовательский интерфейс (и не заставляя все появляться сразу).

У вас будет один JPanel, который будет обрабатывать рисование в методе paintComponent(...), а не paint(...), как в коде выше. Этот JPanel будет перекрашивать каждую Rectangle форму из Shape API.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class DelayedDrawing {
    private JFrame frame;
    private JPanel pane;
    private Timer timer;
    private int xCoord = 0;
    private int yCoord = 0;
    private static final int GAP = 10;
    private static final int WIDTH_HEIGHT = 10;
    private static final int ROWS = 5;
    private static final int COLS = 5;

    private List<Rectangle> rectangles;

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        //We create the JFrame
        frame = new JFrame(this.getClass().getSimpleName());
        //We create a list of Rectangles from the Shape API
        rectangles = new ArrayList<>();
        createRectangle();

        //Creates our JPanel that's going to draw every rectangle
        pane = new JPanel() {
            //Specifies the size of our JPanel
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(150, 150);
            }

            //This is where the "magic" happens, it iterates over our list and repaints every single Rectangle in it
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                for (Rectangle r : rectangles) {
                    System.out.println(r.x + " " + r.y);
                    g2d.draw(r);
                }
            }
        };

        //This starts our Timer
        timer = new Timer(200, listener);
        timer.setInitialDelay(1000);
        timer.start();

        //We add everything to the frame
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //Creates a new Rectangle and adds it to the List
    private void createRectangle() {
        Rectangle r = new Rectangle(xCoord * WIDTH_HEIGHT + GAP, yCoord * WIDTH_HEIGHT + GAP, WIDTH_HEIGHT, WIDTH_HEIGHT);
        rectangles.add(r);
    }

    //This will be executed everytime the Timer is fired
    private ActionListener listener = e -> {
        if (xCoord < ROWS) {
            if (yCoord < COLS) {
                yCoord++;
            } else {
                yCoord = 0;
                xCoord++;
                if (xCoord == ROWS) {
                    timer.stop();
                    return;
                }
            }
        }
        createRectangle();
        pane.repaint();
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DelayedDrawing()::createAndShowGUI);
    }
}

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...