簡體   English   中英

Java Swing 用鼠標點擊和拖動畫線

[英]Java Swing draw lines with mouse click and drag

我想帶回之前問過的一個問題: java draw line as the mouse is moved

“我想在我的應用程序中添加一個功能,允許用戶通過在開始位置單擊鼠標並在結束位置釋放它來繪制一條直線。直線應該隨着鼠標移動而移動,直到它最終被釋放;類似於使用 Microsoft Paint 應用程序繪制線條的方式。

如何實現這一點,以便在不重新繪制可能已經在該矩形區域中繪制的其他內容的情況下,在移動時重新繪制線條?”

問題是:如何在舊線仍然存在的情況下繪制多條線?

這是對我有用的代碼,但是只要你畫一個新的代碼,上一行就會被刪除:

public static void main(String args[]) throws Exception {
    JFrame f = new JFrame("Draw a Red Line");
    f.setSize(300, 300);
    f.setLocation(300, 300);
    f.setResizable(false);
    JPanel p = new JPanel() {
        Point pointStart = null;
        Point pointEnd   = null;
        {
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    pointStart = e.getPoint();
                }

                public void mouseReleased(MouseEvent e) {
                    pointStart = null;
                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseMoved(MouseEvent e) {
                    pointEnd = e.getPoint();
                }

                public void mouseDragged(MouseEvent e) {
                    pointEnd = e.getPoint();
                    repaint();
                }
            });
        }
        public void paint(Graphics g) {
            super.paint(g);
            if (pointStart != null) {
                g.setColor(Color.RED);
                g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
            }
        }
    };
    f.add(p);
    f.setVisible(true); 
}

這是適合我的代碼,但是一旦你繪制一個新代碼就會刪除前一行:

有兩種常見的方法:

  1. 保持要繪制的對象的ArrayList。 然后每次組件需要重繪自身時,paintComponent()方法重新繪制所有對象

  2. 繪制到BufferImage上,然后繪制BufferedImage。

查看自定義繪畫方法 ,了解這兩種方法的工作示例。

只需在 mouseRelesed 中設置

pointStart = e.getPoint instead of pointStart = null.

當您將它設置為 null 時,不需要任何列表或類似的東西,它會從頭開始並刪除最后一個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM