问题是,我试图通过保存鼠标按下、鼠标拖动和最后鼠标释放事件触发的所有点来在面板上画线。我将它们每行保存在 Point[] 点中。我将这些 Point[] 中的每一个添加到 Point[] 的 ArrayList 中。问题是,当我重新绘制线条时,它只打印出最后一行并在该行中留下很多空格,即使它应该连接 2 个点,无论它们有多远。我可能遗漏了一些重要的东西或理解错误。
有人可以看到我做错了什么吗?
代码在这里:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Kimp extends JFrame {
private ArrayList<Point[]> pointsArray = new ArrayList<>();
private Point points[] = new Point[10000];
private int pointCounter = 0;
public Kimp () {
panel paintArea = new panel();
add(paintArea, BorderLayout.CENTER);
}
private class panel extends JPanel {
public panel () {
HandlerClass handler = new HandlerClass();
this.addMouseListener(handler);
this.addMouseMotionListener(handler);
}
@Override
void paintComponent(Graphics g) {
super.paintComponent(g);
try {
for (Point[] p : pointsArray) {
for(int i = 0; i < p.length; i++) {
if (p[i].x == 0) {
continue;
} else {
if (p[i + 1].x == 0) {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i].x, p[i].y);
} else {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
}
}
}
}
points = preFill(points);
} catch (NullPointerException e) {
}
}
}
private class HandlerClass implements MouseListener , MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
points[pointCounter++] = e.getPoint();
//System.out.println("At mouseDragged");
//System.out.println(pointCounter);
//System.out.println(e.getPoint());
}
@Override
public void mousePressed(MouseEvent e) {
//System.out.println("At mousePressed");
//System.out.println(pointCounter);
//System.out.println(e.getPoint());
points[pointCounter] = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
//System.out.println("At mouseReleased: " + points.length);
pointCounter = 0;
pointsArray.add(points);
System.out.println("pointsArray: " + pointsArray.size());
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
public static Point[] preFill (Point[] points) {
for (int i = 0; i < points.length; i++) {
points[i] = new Point(-999,-999);
}
return points;
}
}
和跑步者:
import javax.swing.JFrame;
public class Runner {
public static void main(String[] args) {
Kimp kimp = new Kimp();
kimp.setTitle("Kimp");
kimp.setSize(500, 500);
kimp.setResizable(false);
kimp.setLocation(400, 100);
kimp.setVisible(true);
kimp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
编辑:更新了关于行中空格的代码(固定)。还是不明白为什么它没有画出整排线,只画最后一条……