编辑:这是完整的代码。在每个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);
}
}
答案 0 :(得分:2)
我建议您有两个绘制线条的组件,动态和静态。动态组件是动画过程中的线,为此,您应该在JPanel的paintComponent方法中进行绘制。一旦该线被完全绘制,那么它应该更永久地绘制到BufferedImage上,BufferedImage表示图像的静态部分,也是在paintComponent中绘制的。 paintComponent看起来像这样:
@Override
protected void paintComponent(Graphics g) {
super. paintComponent(g);
// here convert g to Graphics2D and set rendering hints
// to smooth the line via anti-aliasing
if (bufferedImg != null) {
g.drawImage(bufferedImg, 0, 0, null);
}
// a boolean check
if (drawingLine) {
g.drawLine(x1,y1,x2,y2);
}
}
然后在你的Timer的actionListener中你需要条件:
例如
@Override
public void actionPerformed(ActionEvent e) {
if (lineJustNowCompleted) {
drawLineToBufferedImage();
} else if (stillDrawingLine) {
incrementLineEndPoints();
}
repaint();
}
当然魔鬼会在细节中,如果你仍然需要帮助,你需要提供这些细节和更多代码,最好是MCVE。