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值减少的动画,所以它会像箭头一样。根据我收集的内容,我需要使用动作监听器和计时器来完成此任务,但我一直无法确切知道如何做到这一点。如果有人可以请你告诉我在哪里放置以及如何使用计时器和重绘()这样你就可以从线上观看箭头形式我会非常感激。我试图使用这个简单的例子,所以我可以将它改编成更复杂的动画/绘图。
答案 0 :(得分:4)
更新javax.swing.Timer
的actionPerformed()
方法中的坐标,然后调用repaint()
。
答案 1 :(得分: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);
}
}
我明白了。