我试图从一系列鼠标点击中画一条线。
例如,当我从屏幕上的一个点单击到下一个点时,它会连接线,然后我可以继续单击下一个点,它会继续绘制一条连续的绘图线。
一个例子在这里: http: //oneslime.net/java/Tutorial_2在练习 2下
我相信我的逻辑有一些错误(不画线,只是一个点),但我似乎找不到它!
有人可以帮帮我吗?
这是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RoadCreator extends JPanel {
private MouseHandler mouseHandler = new MouseHandler();
private Point previousPoint = new Point();
private Point nextPoint = new Point();
private boolean drawing;
public RoadCreator() {
this.setPreferredSize(new Dimension(640, 480));
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
g.drawLine(previousPoint.x, previousPoint.y, nextPoint.x, nextPoint.y);
}
private class MouseHandler extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
drawing = true;
nextPoint = e.getPoint();
repaint();
previousPoint = e.getPoint();
}
}
public void display() {
JFrame f = new JFrame("Road Creator");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setVisible(true);
}
}
任何帮助将不胜感激,谢谢!