1
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); 
 }

}

所以,我在这里有一些非常基本的代码来从每一端向中间点画一条线。我正在尝试使中间点的 Y 值减小的动画,所以它会像箭头一样。根据我收集到的信息,我需要使用动作侦听器和计时器来完成此操作,但我一直无法弄清楚如何做到这一点。如果有人可以请告诉我在哪里放置以及如何使用计时器和 repaint() 以便您可以从行中观看箭头形式,我将不胜感激。我正在尝试使用这个简单的示例,以便将其调整为更复杂的动画/绘图。

4

2 回答 2

4

actionPerformed()更新yourjavax.swing.Timer和 invoke方法中的坐标repaint()

于 2013-09-29T17:55:56.153 回答
1
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);
  }
}

我想到了。

于 2013-09-30T03:29:19.870 回答