Paul
Paul

Reputation: 58

How can I animate a drawLine?

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

public class Line{

 public static void main(String[] args){

  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.add(new DrawLine(150,300,350,300));
  frame.setSize(500,500);
  frame.setVisible(true);     
 } 
}

class DrawLine extends JPanel{

 int x1;
 int y1;
 int x2;
 int y2;
 int midx;
 int midy;

 public DrawLine(int x1, int y1, int x2, int y2){
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
    midx = (x1+x2)/2;
    midy = (y1+y2)/2;
   }

 public void animateLine(Graphics g){
  g.drawLine(x1,y1,midx,midy);
  g.drawLine(x2,y2,midx,midy);  
 }

 public void paintComponent(Graphics g){
  final Graphics2D g2d = (Graphics2D)g;
  animateLine(g2d); 
 }

}

So, I have a some pretty basic code here to draw a line from each end towards a middle point. I am trying to make an animation of the middle point's Y value decreasing, so it will make something like an arrow. From what I have gathered I will need to use an action listener and a timer to accomplish this, but I have been unable to figure out exactly how to do it. If someone could please enlighten me on where to place and how to use the timer and repaint() so you can watch the arrow form from the line I would greatly appreciate it. I am trying to use this simple example so I can adapt it into a more complicated animation/drawing.

Upvotes: 1

Views: 4665

Answers (2)

Paul
Paul

Reputation: 58

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

public class Line{

 public static void main(String[] args){
  java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(new DrawLine(150,300,350,300));
      frame.setSize(500,500);
      frame.setVisible(true);  
    }
  });  
 } 
}

class DrawLine extends JPanel implements ActionListener{

  int x1;
  int y1;
  int x2;
  int y2;
  int midx;
  int midy;

  Timer time = new Timer(10, (ActionListener) this);

  public DrawLine(int x1, int y1, int x2, int y2){
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
    midx = (x1+x2)/2;
    midy = (y1+y2)/2;
    time.start();
  }

  public void animateLine(Graphics2D g){
    g.drawLine(x1,y1,midx,midy);
    g.drawLine(x2,y2,midx,midy);
  }

  public void actionPerformed(ActionEvent arg0) {
    if(midy>123){
      midy--;
      repaint();
    }
  }

  public void paintComponent(Graphics newG){
    super.paintComponent(newG);
    Graphics2D g2d = (Graphics2D)newG;
    animateLine(g2d);
  }
}

I figured it out.

Upvotes: 1

trashgod
trashgod

Reputation: 205785

Update the coordinates in the actionPerformed() method of your javax.swing.Timer and invoke repaint().

Upvotes: 4

Related Questions