首页 > 解决方案 > 鼠标侦听器 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);
        }
    }

标签: javaswing

解决方案


尝试添加一个 MouseMotionListener 而不是 MouseListener,您可以合并 MouseDragged 方法来绘制。请参阅此处的文档。


推荐阅读