我正在尝试使用 Point 类和 arraylist 在 java 中编写一个简单的自由手绘代码,但我被卡住了。首先,不能真正离开原点,其次,即使不拖动鼠标,两点之间也总是画一条线。
public class FreeDraw extends Applet implements MouseMotionListener
{
int x,y,m,n;
ArrayList<Point> al;
public void init()
{
al = new ArrayList<>();
this.addMouseMotionListener(this);
}
public void paint(Graphics g)
{
for(int i=0;i<al.size();i++)
{
m=al.get(i).x;
n=al.get(i).y;
g.drawLine(m,n,x,y);
x=m;
y=n;
}
}
public void mouseDragged(MouseEvent e)
{
al.add(new Point(e.getX(),e.getY()));
repaint();
}
public void mouseMoved(MouseEvent e)
{
//do nothing
}
}
最佳答案
您需要为初始 x/y 位置设置种子(否则 m
和 n
将是 0x0
到第一个点)
有点像...
@Override
public void paint(Graphics g) {
super.paint(g);
if (!al.isEmpty()) {
int x = al.get(0).x;
int y = al.get(0).y;
for (int i = 1; i < al.size(); i++) {
m = al.get(i).x;
n = al.get(i).y;
g.drawLine(m, n, x, y);
x = m;
y = n;
}
}
}
例如。
除了 Applet
大约在 16 年前被 JApplet
取代之外,Oracle 不再支持 applet 插件,但大多数浏览器都主动阻止它,使其成为死胡同的技术。
参见 Java Plugin support deprecated和 Moving to a Plugin-Free Web了解更多详情
关于java - 使用 Point 类在 Java 中自由手绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427705/