【发布时间】:2017-01-01 10:14:30
【问题描述】:
所以,我想使用带有 swing 的 java 来实现 DDA 算法来绘制线条,但我这里有一点问题。要绘制每个像素,我使用fillRect(X,Y,1,1)。所以,我需要为X和Y的不同位置画一条线。为了更新新绘制的“像素”,我使用了revalidate() 和repaint(),但这似乎删除了我之前绘制的像素,我只看到了一点。作为一种解决方法,我在paintComponent(Graphics) 中注释掉了super.paintComponent(g),但这似乎不是一个好的解决方案,因为我无法设置背景颜色,并且如果我使用Thread.sleep() 减慢它的速度,我会看到线条被绘制(否则我只看到一个点)。这是代码
import javax.swing.*;
import java.awt.*;
public class Painter extends JPanel {
private double x1,y1,x2,y2;
Painter(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
@Override
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
setBackground(Color.black);
g.setColor(Color.RED);
g.fillRect((int)x1,(int)y1,1,1);
}
public void drawLine() {
double DX = (x2-x1);
double DY = (y2-y1);
double steps = (Math.abs(DX) > Math.abs(DY) ) ? Math.abs(DX) : Math.abs(DY);
double xIncrement = DX/(steps);
double yIncrement = DY/(steps);
try {
for (int i = 0; i < steps; ++i) {
Thread.sleep(50);
x1 += xIncrement;
y1 += yIncrement;
revalidate();
repaint();
}
}
catch (Exception e) {
}
}
}
从我的main() 我这样称呼它
JFrame jFrame = new JFrame("Graphics");
Painter dpl = new Painter(0,0,533,333);
jFrame.add(dpl);
jFrame.setSize(720,480);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dpl.drawLine();
如何解决?
【问题讨论】:
-
你应该从一个单独的线程调用
drawLine。repaint可以安全地从 EDT 外部调用,您可以通过调用drawLine(其中包含sleep())来阻止 EDT。