java - 鼠标侦听器 Java Swing 无法绘制连续线
问题描述
如何在由rectengle 制作的JPanal 中绘制连续线。
我的代码:
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
points.add(new Point(x, y));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
g2d.setColor(Color.BLACK);
drawRectangles(g2d);
drawLines(g2d);
}
points 是一个存储我的矩形的列表。
我想在按下的按钮上画连续的线,但我所得到的只是每次点击一个矩形。
private void drawRectangles(Graphics2D g2d) {
int x, y;
for (Point p : points) {
x = (int) p.getX();
y = (int) p.getY();
g2d.fillRect(x, y, 10, 10);
}
}
解决方案
尝试添加一个 MouseMotionListener 而不是 MouseListener,您可以合并 MouseDragged 方法来绘制。请参阅此处的文档。
推荐阅读
- excel - Excel vba 公式字符串不计算:#NAME?错误
- java - Java - 收件箱中的新邮件
- c# - 如何在发送密钥之前清除文本字段 selenium c#
- java - Mule maven 依赖错误 - 使用 com.sun.jersey 的 REST 调用
- r - 使用聚合按行匹配值
- java - 在java中为android重新组合拆分字符串
- html - 在水平菜单子菜单 Css 无法正常工作
- function - FUNCTION 调用问题中的 PL/SQL 集合
- nginx - 无法使用 helm 在 AWS 上的 kops 集群上安装 nginx
- sql-server - 如何结合这两个查询?