单击新位置时如何阻止形状消失?

时间:2015-11-19 20:01:29

标签: java jframe jpanel mouseevent actionlistener

我编写了这段代码,用鼠标点击显示形状,但我有问题。当我点击新位置时,形状会消失在前一个位置上。我怎么能阻止这种情况发生?

头等舱:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MouseClick {
    private static int x,y;
    private static DrawingObjects object = new DrawingObjects();

    public static void main(String[] args){

        JFrame frame = new JFrame("MouseClick");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.add(object);
        object.addMouseListener(new AL());
    }
    static class AL extends MouseAdapter{
        public void mouseClicked (MouseEvent e){
            x = e.getX();
            y = e.getY();
            object.drawing(x, y);
        }
    }
}

第二课:

import javax.swing.*;
import java.awt.*;

public class DrawingObjects extends JPanel{
    private static int x,y;

    public void drawing(int xx, int yy){
        x = xx;
        y = yy;
        repaint();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.fillRect(x, y, 20, 20);
    }
}

1 个答案:

答案 0 :(得分:1)

处理此问题的最佳方法是跟踪已点击的每个点,并在paintComponent中重新绘制每个点。

所以将private static int x, y更改为private List<Point> points = new ArrayList<>(),然后添加到其中:

public void drawing(int x, int y){
    points.add(new Point(x, y));
    repaint();
}

然后在重绘时浏览每个点:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    for(Point p : points){
        g.fillRect(p.x, p.y, 20, 20);
    }
}