【发布时间】:2015-03-21 12:27:40
【问题描述】:
编辑:这是完整的代码。在执行每个 actionPerformed 之后,我需要在执行 repain() 之前更改 x1、y1、x2、y2 和 t 的值。有没有一种简单的方法可以做到这一点?我只上过一门 Java 基础课,所以尽量保持在初级水平。
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(0,0,0,0));
frame.setSize(500,500);
frame.setVisible(true);
}
});
}
}
class DrawLine extends JPanel implements ActionListener {
int x1;
int y1;
int x2;
int y2;
int i=100;
int j=50;
int t=1000;
Timer time = new Timer(t, (ActionListener) this);
public DrawLine(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
time.start();
}
public void animateLine(Graphics2D g) {
g.drawLine(x1,y1,x2,y2);
}
public void actionPerformed(ActionEvent arg0) {
x2=x2+i;
y2=y2+j;
time.stop();
time.start();
repaint();
}
public void paintComponent(Graphics newG) {
super.paintComponent(newG);
Graphics2D g2d = (Graphics2D)newG;
animateLine(g2d);
}
}
【问题讨论】:
-
可能的建议:将动画线绘制到JPanel 的paintComponent 方法覆盖(您没有显示),并将完成的线绘制到同样在paintComponent 中绘制的BufferedImage。是的,编辑你的代码,使其可读。强迫这里的人们阅读难以阅读的代码并不是一种好的形式。
-
抱歉,如果每行缩进 4 个空格,则此处不会显示为“代码”。
-
停止道歉并按照我的建议发布 MCVE。
-
是的,只要你在该方法中加入一些逻辑,包括 if 条件,它就可以在 actionPerformed 中完成。但我也赞同@AndrewThompson 的建议,请发布您的mcve,以便我们更轻松地学习和运行您的代码。
标签: java swing animation time line