ImGone98
ImGone98

Reputation: 195

Drawing a line non instantaneous

How would you draw a line, but not in an instant, but slowly like you would actually be drawing a line on a piece of paper. Also how would you control the speed of drawing the line? The main is in another class that just starts the program.

public class Moving extends JPanel implements ActionListener {
    Timer time = new Timer(5000, this);
    boolean rotation1 = false;
    public Moving() {
        addKeyListener(new TAdapter());
        setFocusable(true);
        initGame();


    }
    public void initGame() {
        time.start();
    }

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.setBackground(Color.RED); 
    if(rotation1) {
        for(int p = 0; p < 600; p++) {
            this.setBackground(Color.BLUE);
            g.drawRect(10, p, 20, 20);
        }

    }
    }


    public void start() {
        Moving game = new Moving(); 
        JFrame frame = new JFrame("Frame"); 
        frame.setSize(320, 340);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(game); 
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        repaint();

    }
    private class TAdapter extends KeyAdapter {
        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if(key == KeyEvent.VK_1) {
                rotation1 = true;
            }           
                    }

        public void keyReleased(KeyEvent e) {
        }
    }
}

Upvotes: 0

Views: 56

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

You can't try and perform animation within the paintComponent method. This will block the Event Dispatching Thread, preventing from actually painting anything (amongst other things).

What you need to do is wait in the background for a specific period of time and then update the state and repaint.

While, there are a number of way so achieve this, the easiest is to use a javax.swing.Timer

This allows you to specify a delay period, which when triggered, it makes the call back within the context of the EDT making it safe to update the UI from within

Take a look at Event Dispatching Thread and How to use Swing Timers for more details

Upvotes: 6

Related Questions